reactjs - 将道具传递给子组件时如何在 onChange 中设置状态?
问题描述
当我将道具传递给子组件时,我无法在 onChange 函数中分配状态。我有一个表单,当用户提交它应该更新状态。
过去,我设置了状态,但没有传递道具,因为它在同一个文件中,但现在我在函数中使用道具,我不确定如何设置状态。
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>
)}
解决方案
您需要将 acallback function
作为prop
.
props.onChange
然后在您的 Parent 组件中使用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>
);
}
}
如果您想要 Child 处理自己的状态,那么您可以使用 React 钩子并将状态添加到功能组件(请参阅useState
或useReducer
钩子https://reactjs.org/docs/hooks-reference.html#usestate,或制作它一个类组件。
推荐阅读
- javascript - 如何使 axios 发布到 ReactJS 中的数据库?
- sql-server - 从开始日期和结束日期构建时间表
- javascript - Z-Index 固定位置 iframe 出现在 iO 上的身体后面?
- amazon-redshift - 创建数据集时出错:(table_name) 在 redshift 中找不到 mixpanel 数据的表
- html - 如何使 CSS 网格对其中的变化元素无响应?
- javascript - Bootstrap V5 Modal 不通过 Javascript 隐藏,除非 Window 方法
- python - 如果 type(other) == str 则覆盖 MyClass 中的 '__rmod__' 不起作用
- c# - XML-RPC Odoo - C# 使用运算符或的多个搜索条件
- php - 找不到类 'app\Models\Job' 为什么?该怎么办?
- amazon-web-services - 在 Athena 中对表进行分区