[英]React-Native - I can not use State string as new list element
Yesterday I started learning React Native. 昨天我开始学习React Native。 Unfortunately I encounter some difficulties right at the beggining. 不幸的是,我刚开始时遇到了一些困难。 I was trying to write simple list, which contains some input, and when user clicks "Add new" button, list will extend with new item. 我试图写一个简单的列表,其中包含一些输入,当用户单击“添加新”按钮时,列表将扩展为新项目。 When I am trying to use this.state.newName variable in a new list element React is throwing me exception: 当我尝试在新的列表元素中使用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." “始终违规:对象作为React子对象无效(找到:带有键{dispatchConfig,_targetInst,isDefaultPrevented,isPropagationStopped,_dispatchListeners,_dispatchInstances,类型,目标,currentTarget,eventPhase,气泡,可取消,timeStamp,defaultPrevented,isTrusted, })。如果您要呈现子级集合,请改用数组。”
My code is really simple: 我的代码非常简单:
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>
);
}
} }
When I am not using this.state.newName, and just pass some string like: 当我不使用this.state.newName时,只需传递一些字符串,如:
let newName = "Adam";
It will works just fine. 它将正常工作。 What can be a cause? 可能是什么原因?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.