让子组件互相交谈

时间:2018-07-17 06:49:31

标签: reactjs

我知道这已经被问过了,但是我已经玩了一段时间了,但是我没有得到。我有两个由父级page使用和连接的子级组件。第一个子组件是一个表单,第二个子组件是一个包含所有userProfiles列表的表。提交表单时,我想告诉表格组件运行一个函数。我该怎么做?

路径:Parent Component

export default class StudentPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  render() {
    return (
      <div>
        <AddStudentForm
          guardianUserProfiles={this.props.guardianUserProfiles}
        />
        <StudentTable
          studentUserProfiles={this.props.studentUserProfiles}
        />
      </div>
    );
  }
}

路径:AddStudentForm

export default class AddStudentForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
  }

  render() {
    return (
      <Form onSubmit={this.handleSubmit} className="mb-3">
        <Input
          type="text"
          name="firstName"
          value={this.state.firstName}
          onChange={this.handleInputChange}
          id="firstName"
          placeholder="First name"
        />
        <button type="submit" className="btn btn-primary">Save</button>
      </Form>
    );
  }
}

路径:StudentTable

export default class StudentTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };

    this.handleTableUpdate = this.handleTableUpdate.bind(this);
  }

  handleTableUpdate = () => (event) => {
    // Do stuff
  }

  render() {
    return (
      <div>
        <Table hover bordered responsive>
          <thead>
            <tr>
              <th className="border-left border-top-0 border-right-0 pt-0">#</th>
              <th className="border-left-0 border-top-0 border-right-0 pt-0">First name</th>
            </tr>
          </thead>
          <tbody>
            {this.state.userProfile.map((studentUserProfile, idx) => (
              <tr>
                <React.Fragment>
                  <th rowSpan={studentUserProfile.classes.length} className="border-left aling-double-row">{idx + 1}</th>
                  <td rowSpan={studentUserProfile.classes.length} className="aling-double-row">{studentUserProfile.firstName}</td>
                </React.Fragment>
              </tr>
            ))}
          </tbody>
        </Table>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:4)

方法1: 您可以使用flux或redux

实现此目的

方式2: 您可以将回叫表单child1(即带有表单的页面)发送给父级,并将其作为道具从父级发送到child2(即带有表格的页面)。

相关问题