OGeek|极客世界-中国程序员成长平台

标题: javascript - React Native TextInput setState() 问题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:58
标题: javascript - 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;
}
}



Best Answer-推荐答案


在你的 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"
/>

关于javascript - React Native TextInput setState() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49606526/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4