【发布时间】:2019-12-31 01:30:21
【问题描述】:
我有一个基于 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 未定义。如何根据子组件单击的元素更新 QuestionsSection 的(父组件)状态?是把子组件中被点击元素的值传回父组件的问题吗?
【问题讨论】:
标签: javascript reactjs onclick components react-props