我有一个基于React类的组件。我想从这个父组件中传递一个子组件函数。当子组件执行onClick事件时,我将调用父函数。然后,我希望根据在子组件中单击的元素更新父组件中的状态。
QuestionsSection是具有状态的父组件:
class QuestionsSection extends React.Component {
constructor(props) {
super(props);
this.state = {
isVisible: "option1"
};
}
handleOptionChange = e => {
this.setState({
isVisible: e.target.value
});
alert("function called");
}
render() {
return (
<div>
<QuestionsItems
isVisible={this.state.isVisible}
handleOptionChange={() => this.handleOptionChange()}
</div>
);
}
}QuestionsItems是无状态/功能组件的子组件:
const QuestionsItems = (props) => {
return (
<div>
<Container className="d-flex flex-md-row flex-column justify-content-center">
<Row className="d-flex flex-md-column flex-row order-1 justify-content-center">
<Col className={props.isVisible === 'option1' ? 'highlighted' : 'questions-section'}>
<label className="cursor-pointer" onClick={props.handleOptionChange}>
<input
type="radio"
value="option1"
checked={props.isVisible === 'option1'}
onChange={props.handleOptionChange}>
</input>
<Col xs={{span: 12}}>
<img src={questions1} alt="pic" height="50"/>
</Col>
<p>Ask a question</p>
</label>
</Col>
<Col className={props.isVisible === 'option2' ? 'highlighted' : 'questions-section'}>
<label className="cursor-pointer" onClick={props.handleClick}>
<input
type="radio"
value="option2"
checked={props.isVisible === 'option2'}
onChange={props.handleOptionChange}>
</input>
<Col xs={{span: 12}}>
<img src={questions2} alt="pic" height="50"/>
</Col>
<p>Vote on everything</p>
</label>
</Col>
</Row>
<Row className="d-flex flex-md-column flex-row image-container order-md-2 order-3 justify-content-center">
<Col
xs={{span: 12}}
className="featured-question order-lg-2 order-3">
{
props.isVisible === 'option1' ?
<Col xs={{span: 12}}>
<img src={questionsBig1} alt="featured image"/>
</Col>
: ""
}
{
props.isVisible === 'option2' ?
<Col xs={{span: 12}}>
<img src={questionsBig2} alt="featured image" />
</Col>
: ""
}
</Col>
</Row>
</Container>
</div>
);
}这个组件有很多标记/引导语法。忽略这一点,这只是两个元素,它们都有一个onClick事件。第三部分是基于值显示第一个或第二个元素的三元逻辑。
我遇到的问题在于更新父组件中的this.state。e.target.value是未定义的。如何根据子组件单击的元素更新问题部分的(父组件)状态?是否将子组件中单击元素的值传递回父组件?
以下是错误:

发布于 2019-08-26 21:17:22
您需要传递handleOptionChange作为handleOptionChange支柱的回调。
改变这一点:
handleOptionChange={() => this.handleOptionChange()}至
handleOptionChange={this.handleOptionChange}这是因为处理程序需要一个未传递给函数的事件。
发布于 2019-08-26 21:17:00
在父类中,不向当前调用setState()的处理程序传递任何参数。您需要将从子处理程序传递的值传递给处理程序,在此是更改事件。在进行以下更改之前,尝试在handleOptionChange中注销handleOptionChange,您将看到它是未定义的。尝试以下几点:
handleOptionChange={(e)=> this.handleOptionChange(e)}您还可以缩短以下内容:
handleOptionChange={this.handleOptionChange}希望这能帮上忙!
https://stackoverflow.com/questions/57664983
复制相似问题