im试图更改父类调用ed welcom.js中article2状态的状态 onclick函数位于子类quiz.js中。所以在单击该函数时,我想更改父类中的状态状态有什么帮助吗?
父类状态
我想在子类的函数中将其更改为true
article1: false,
article2: false,
article3: false,
article4: false,
article5: true
子类功能
loadNextChallenege = () => {
if (this.props.rankValue === 1) {
this.setState({
//article state
});
} else if (this.props.rankValue === 2) {
this.setState({
//article state
});
}
};
答案 0 :(得分:1)
通过props从父级传递一个函数,然后在子级中调用它(并传递任何必要的参数)
父示例
function updateState(value){
this.setState({
//article state
});
}
<Child updateState={this.updateState} />
然后在孩子里
loadNextChallenege = () => {
this.props.updateState("a value");
}
答案 1 :(得分:0)
父组件
import Child from './Child';
class Parent extends React.Component {
state={
something:''
}
getFromChild(data){
this.setState({something:data })
}
render() {
return (
<div>
<Child
sendToParent={this.getFromChild} // catch child state
/>
</div>
)
}
}
子组件
class Child extends React.Component {
state={
userInput:''
}
handleChange(e){
this.setState({
[e.target.name]: e.target.value, //update state as user enters input
})
}
handleClick(e){
this.props.sendToParent(this.state.userInput) //pass child state up to parent
}
render() {
return (
<div>
<input
name='entry'
value={this.state.userInput}
onChange={this.handleChange}
/>
<Button onClick={this.handleClick}><span>Send State To
Parent</span></Button>
</div>
)
}
}
每次用户输入的内容都会保存在子组件的状态中,单击按钮时,状态将被发送到父组件,您可以如上所述从父组件中捕获它。如果您听不懂或有任何疑问,请告诉我。