React Native TextInput setState() 问题

新手上路,请多包涵

我在 TextInput 的 onChangeText 中遇到 React Native 的 this.setState() 问题。我试图在其下方的 Text 标记中显示 TextInput 的内容。但是,它什么也不显示——setState() 调用永远不会更改 this.state.searchtext。我也没有错误。预先感谢您的帮助!这是我的代码:

  export default class ShowScreen extends Component {
constructor(props) {
    super(props);
    this.state = {
        searchtext: ""
    };
}
render() {
    var thisscreen = (
        <View>
            <ScrollView
                horizontal={true}
                showsHorizontalScrollIndicator={false}
                pagingEnabled={true}
            >
                <View
                    style={{
                        flex: 1,
                        height: totalheight,
                        justifyContent: "space-around",
                        alignItems: "center",
                        width: totalwidth,
                        backgroundColor: "#FF0000"
                    }}
                >
                    <TextInput
                        style={{ height: 80, fontSize: 20 }}
                        placeholder="placeholder"
                        value={this.state.searchtext}
                        onChangeText={searchtext =>
                            this.setState({ searchtext })
                        }
                        ref={input => {
                            this.textInput = input;
                        }}
                        returnKeyType="go"
                    />
                    <Text>{this.state.searchtext}</Text>
                </View>
            </ScrollView>
        </View>
    );
    return thisscreen;
}
}

原文由 Hobbes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 261
1 个回答

在你的 TextInput 添加 value prop

 <TextInput
 style={{height: 80, fontSize: 20}}
 placeholder="placeholder"
 value={this.state.searchtext}
 onChangeText={(searchtext) => this.setState({ searchtext })}
 ref={input => { this.textInput = input }}
 returnKeyType="go"
/>

原文由 Adeel Imran 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题