当我将属性传递给子组件时,在我的onChange函数中分配状态时遇到了问题。我有一个表单,当用户提交时,它应该更新状态。
在过去,我设置了state,但没有传递props,因为它在同一个文件中,但现在我在一个函数中使用props,我不确定如何设置state。
const Child = props => {
return (
<div className='form'>
<Form >
<Form.Row>
<Col>
<Form.Control
name="studentName"
value={props.studentName}
placeholder="Student name"
onChange={this.change}
/>
</Col>
<Col>
<Form.Control
name="studentId"
value={props.studentId}
placeholder="StudentID"
onChange={e => this.change(e)}
/>
</Col>
</Form.Row>
</Form>
</div>
)}发布于 2019-04-09 04:00:11
您需要将callback function作为prop传递给子组件。
props.onChange
然后在父组件中使用setState处理状态。
有关更多信息,请查看此处:https://reactjs.org/docs/faq-functions.html
下面是一个示例:
const Child = props => {
return (
<form onSubmit={props.onSubmit}>
<input
type="text"
name="studentName"
value={props.studentName}
placeholder="Student name"
onChange={props.onChange}
/>
<button type="submit">submit</button>
</form>
);
};
class Parent extends React.Component {
state = {
data: ""
};
handleChange = e => {
this.setState({
data: e.target.value
});
};
handleSubmit = e => {
e.preventDefault();
console.log(this.state.data);
};
render() {
return (
<div>
<Child onSubmit={this.handleSubmit} onChange={this.handleChange} />
<p>{`state: ${JSON.stringify(this.state.data)}`}</p>
</div>
);
}
}如果您想让子对象处理自己的状态,那么您可以使用React钩子并将状态添加到函数组件(请参阅useState或useReducer钩子https://reactjs.org/docs/hooks-reference.html#usestate,或者使其成为类组件)。
https://stackoverflow.com/questions/55580863
复制相似问题