javascript - React-Native - 我无法使用状态字符串作为新的列表元素

标签 javascript reactjs react-native native expo

昨天我开始学习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/

相关文章:

javascript - 调用 URL 并获取返回值。 Jquery和Javascript都不显示返回值

javascript - 使用 React 和 Flask 静态模板渲染 CSS

javascript - 将内联样式更改为样式组件

javascript - react 原生 + react 原生路由器通量 : Why is background color white during transition?

react-native - 在 expo 应用程序中安装 magnus-ui 后出现错误 "No Space between hexadecimal literal and identifier"

android - 程序类型已经存在 : androidx. versionedparcelable.NonParcelField

javascript - 需要值(减去值)来影响另一个输入的值

javascript - react 多重加载状态

reactjs - 同时对 Asp.Net core 2.0 MVC 应用程序 (cookie) 和 REST API (JWT) 进行身份验证

javascript - onclick 不触发 jquery 中的所有代码