首页 > 解决方案 > 将道具传递给子组件时如何在 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>
)}

标签: reactjsstateonchangereact-props

解决方案


您需要将 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 钩子并将状态添加到功能组件(请参阅useStateuseReducer钩子https://reactjs.org/docs/hooks-reference.html#usestate,或制作它一个类组件。


推荐阅读