昨天我开始学习React Native。不幸的是,我在一开始就遇到了一些困难。 我试图编写简单的列表,其中包含一些输入,当用户单击“添加新”按钮时,列表将扩展新项目。当我尝试在新列表元素中使用 this.state.newName 变量时,React 抛出异常:
" Invariant Violation: Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, isDefaultPrevented, isPropagationStopped, _dispatchListeners, _dispatchInstances, type, target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, nativeEvent}). If you meant to render a collection of children, use an array instead."
我的代码非常简单:
export default class HelloWorldApp extends Component {
constructor() {
super();
this.state = {
newName: "",
peopleList: [
{ key: "1", name: "Jonathan", lastname: "Smith" },
{ key: "2", name: "Tomasz", lastname: "Kowalski" },
{ key: "2", name: "Adrian", lastname: "Jakubowski" },
]
}
}
addNew() {
let newName = this.state.newName;
this.setState({
peopleList: [...this.state.peopleList, {key: newName, name: newName, lastname: "Added"}]
});
}
render() {
return (
<View style={styles.peopleList}>
<Text>People I know:</Text>
<TextInput
value={this.state.newName}
onChange={(text) => this.setState({newName: text})}
/>
<Button title="Add new!"
onPress={() => this.addNew()}
/>
<FlatList
data={this.state.peopleList}
renderItem={({ item }) => <Text style={styles.item}>Imie: {item.name} Nazwisko: {item.lastname}</Text>} />
</View>
);
}
}
当我不使用 this.state.newName 时,只需传递一些字符串,例如:
let newName = "Adam";
它会工作得很好。可能是什么原因?
最佳答案
更改此:
onChange={(text) => this.setState({newName: text})}
致:
onChangeText={(text) => this.setState({newName: text})}
正确的 Prop 是onChangeText
你可以在 here 中看到它的用法
关于javascript - React-Native - 我无法使用状态字符串作为新的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53032503/