将props传递给子组件时如何在onChange中设置状态?

问题描述 投票:0回答:1

当我将道具传递给子组件时,我在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>
)}
reactjs state onchange react-props
1个回答
1
投票

您需要将callback function作为prop传递给您的Child组件。

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>
    );
  }
}

如果你想要的是Child来处理它自己的状态,那么你要么使用React钩子并将状态添加到一个函数组件(参见useStateuseReducer hooks https://reactjs.org/docs/hooks-reference.html#usestate,或者使它成为一个类组件。

© www.soinside.com 2019 - 2024. All rights reserved.