繁体   English   中英

React-Native-我不能将状态字符串用作新的列表元素

[英]React-Native - I can not use State string as new list element

昨天我开始学习React Native。 不幸的是,我刚开始时遇到了一些困难。 我试图写一个简单的列表,其中包含一些输入,当用户单击“添加新”按钮时,列表将扩展为新项目。 当我尝试在新的列表元素中使用this.state.newName变量时,React抛出异常:

“始终违规:对象作为React子对象无效(找到:带有键{dispatchConfig,_targetInst,isDefaultPrevented,isPropagationStopped,_dispatchListeners,_dispatchInstances,类型,目标,currentTarget,eventPhase,气泡,可取消,timeStamp,defaultPrevented,isTrusted, })。如果您要呈现子级集合,请改用数组。”

我的代码非常简单:

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})}

正确的道具是onChangeText

你可以在这里看到它的用法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM