【发布时间】:2019-01-21 08:34:44
【问题描述】:
我是反应初学者。现在我正在尝试添加基于服务器数据的动态 TextInputs,我无法获取每个文本字段的数据。以下是我当前的代码
renderData() {
var questionArray = getDataFromServer();
var lIndex = -1;
const views = questionArray.map((item, index) => {
if (item === "__TEXT__") {
lIndex++;
return (
<LineInput
placeholder=""
onChangeText={text => this.onTextChanged(lIndex, text)}
value={this.state.otherText[lIndex]}
key={index}
/>
);
}
return <Text key={index}>{item + " "}</Text>;
});
return views;
}
onTextChanged = (index, value) => {
console.log("Text Index:" + index);
const Textdata = [...this.state.otherText];
Textdata[index] = value;
this.setState(
{
otherText: Textdata
},
() => {
console.log("Text data = " + this.state.otherText);
}
);
};
这是我的 LineInput.js 文件
import React from "react";
import { View, StyleSheet, TextInput } from "react-native";
const LineInput = ({
value,
onChangeText,
placeholder,
secureTextEntry,
keyboardType,
autoCapitalize
}) => {
return (
<View style={styles.container}>
<TextInput
autoCorrect={false}
onChangeText={onChangeText}
placeholder={placeholder}
style={styles.input}
secureTextEntry={secureTextEntry}
value={value}
underlineColorAndroid="transparent"
keyboardType={keyboardType}
autoCapitalize={autoCapitalize}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
width: 150,
borderColor: "black",
borderBottomWidth: 1
},
input: {
color: "black",
width: "100%",
height: "100%",
backgroundColor: "white",
fontSize: 14
}
});
export { LineInput };
现在的问题是,无论我从哪个字段开始输入,所有数据都会在最后一个文本字段中输入。日志始终将 Text 索引显示为最后一个索引,并且在 Text 数据中,所有数据都在数组的最后一项中输入。我在这里做错了吗,如果是这样,解决这个问题的正确方法是什么。
【问题讨论】:
标签: react-native dynamic react-native-android react-native-ios textinput