![](/img/trans.png)
[英]setState is not updating for TextInput using hooks in React Native
[英]React Native TextInput setState() issue
我在 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;
}
}
在您的TextInput
添加value
道具
<TextInput
style={{height: 80, fontSize: 20}}
placeholder="placeholder"
value={this.state.searchtext}
onChangeText={(searchtext) => this.setState({ searchtext })}
ref={input => { this.textInput = input }}
returnKeyType="go"
/>
嘿,您使用了一個變量來存儲屏幕代碼,即 thisscreen。 這可能會阻止它更新狀態。
你的渲染函數應該是這樣的:
render () {
return (
<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>);
}
onChangeText={(search_text) => this.setState({searchtext:search_text})}
試試這個,那可能會起作用。
我認為 React onChangeText
方法中可能存在錯誤。 你只需要更換onChangetText
到onChange
然后將正常工作。
<TextInput
style={{height: 80, fontSize: 20}}
placeholder="placeholder"
onChange={(text) => this.setState({searchtext : text})}
ref={input => { this.textInput = input }}
returnKeyType="go"
/>
當您使用 setState 時,我們提供一個 JSON 作為參數。 請按照下面的代碼。
<TextInput
style={{height: 80, fontSize: 20}}
placeholder="placeholder"
value={this.state.searchtext}
onChangeText={(searchtext) => this.setState({ searchtext: searchtext })} // <--
ref={input => { this.textInput = input }}
returnKeyType="go"
/>
如果它不起作用,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.