使用react.js

时间:2018-01-18 10:15:55

标签: javascript reactjs ecmascript-6

如何将孩子的状态传回容器?我有一个非常简单的应用程序,但因为我将它们拆分为更小的组件,现在我将状态值(Form)传递回其容器。我也可以在子组件中调用api,然后通过props容器接收它,但这不是干净的,我希望将'final event'放在容器中,并且容器具有'main'状态。

我的第一个意图(确保'主'状态存储在容器中)是否正确?如果是,如何将状态从子组件传回给容器?假设我没有使用redux。

https://codesandbox.io/s/8zrjjz3yjj

2 个答案:

答案 0 :(得分:4)

将方法作为道具传递:

父:

class Parent extends Component {
    ....

    render = () => <Child onChange={childDidSomething}/>

    childDidSomething = state => {
        ...
    }
}

子:

class Child extends Component {
    ....

    render() {...}

    somethingChanged() {
        this.props.onChange(this.state);
    }
}

答案 1 :(得分:1)

你应该lift the state up

让父组件处理与其子项有关的状态,并将处理程序传递给子项,以便子项可以调用它们并将它们传回相关值。

以下是使用您的代码运行此方法的示例:

&#13;
&#13;
class AddUser extends React.Component {

  onChange = ({ target }) => {
    const { onChange } = this.props;
    onChange(target.value);
  }

  render() {
    return (
      <div>
        <input onChange={this.onChange}
          type='text' placeholder='user' />
      </div>
    )
  }
}

class Modal extends React.Component {

  state = { newUser: '' }

  onUserChange = newUser => this.setState({ newUser });

  addUser = () => {
    const { addUser } = this.props;
    const { newUser } = this.state;
    addUser(newUser);
    this.setState({ newUser: '' }); // reset the field
  }

  render() {
    return (
      <div>
        <AddUser onChange={this.onUserChange} />
        <button onClick={this.addUser}>add</button>
      </div>
    )
  }
}

class MainContainer extends React.Component {

  state = {
    showAddUser: false,
    users: [{
      name: 'Jane'
    }, {
      name: 'Black'
    }]
  }

  addUserIntoUsers = (userName) => {
    const { users } = this.state;
    if (userName) { // only if we have a value
      const nextUsers = [...users, { name: userName }];
      this.setState({ users: nextUsers, showAddUser: false });
    }
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ showAddUser: !this.state.showAddUser })}>
          Toggle User Panel
        </button>
        <br />
        {this.state.users.map(o => {
          return (<div>{o.name}<br /></div>)
        })}
        {this.state.showAddUser && <Modal addUser={this.addUserIntoUsers} />}
      </div>
    )
  }
}

ReactDOM.render(<MainContainer />, document.getElementById('root'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
&#13;
&#13;