[英]How to change parent's state from child component in react native?
我有一個看起來像這樣的父組件App.js
export default class App extends React.Component {
constructor(){
super();
this.state = {
registerusername: '',
}
}
現在,我有一個子組件ChildComp.js,它是App.js的直接子代,看起來像這樣
class ChildComp extends React.Component {
render() {
return (
<View>
<TextInput
placeholder="Username"
placeholderTextColor = 'black'
onChangeText={(registerusername) => this.setState({registerusername})}
/>
<Text>
{this.state.registerusername.split(' ').map((word) => word && '🍕').join(' ')}
</Text>
</View>
}
}
我正在嘗試更改比薩餅徽標的打印,就像TextInput字段下的react native文檔一樣。 當狀態, registerusername
在父組件中並且ChildComp是無狀態時,我很難理解如何執行此操作。 我在ChildComp中正在執行“ this.setState({registerusername})},但我不認為它是在引用父級的狀態。
在應用中”
setName = (name) => {
this.setState({ registerusername: name })
}
render() {
return (
<div>
<ChildComp registerusername={this.state.registerusername} setName={this.setName} />
</div>
)
}
在ChildComp中
< TextInput
placeholder = "Username"
placeholderTextColor = 'black'
onChangeText = {(e) => this.props.setName(e.target.value)}
/>
< Text >
{ this.props.registerusername.split(' ').map((word) => word && '🍕').join(' ') }
</Text >
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.