React:将 child 新插入的元素返回给 parent 以更新状态

React: Give back the child new inserted element to parent for update the state

我在 React 中有一个显示项目列表的 parent 组件,也是 (selectedList) 的状态,它为这个列表项目提供一个活动的 class + 显示其他组件取决于活动 class。这是 parent 组件。

在 child 中,我显示可以设置新列表的表单和 onSubmit 事件,我将其插入集合 (meteor+mongo)

问题是我无法在新项目 (id) 和 parent 组件之间建立关系,因为我想 select 新创建的列表(所以给 active class 并显示其他组件)。然后我想我应该更新 state.selectedListId 但我不知道如何在 child 中将它发送到 parent 组件?

下面是几行代码:

PARENT 元素(页)

class TodosPage extends Component {

constructor(props) {
    super(props);
    this.state = {
        listSelected: "",
    };
}

selectList(listId) {
    this.setState({ listSelected: listId });
}

renderLists() {
    return this.props.lists.map((list) => (
        <List 
            selectedItemId={this.state.listSelected}
            selectList={() => this.selectList(list._id)}
            key={list._id}
            list={list}
            countPendingTasks={this.countPendingTasks(list._id)}
        />
    ));
}

render() {
    return (
        <div className="container">
                <ListForm />
                <ListGroup>
                    {this.renderLists()}
                </ListGroup>

CHILD ELEM(列表形式)

handleSubmit(event) {
    event.preventDefault();

    const name = ReactDOM.findDOMNode(this.refs.nameInput).value.trim();
    Meteor.call('lists.insert', name, (err, listId) => {
        console.log("in method insert = " + listId);
        // HERE I CAN HAVE THE GOOD ID
    });
    ReactDOM.findDOMNode(this.refs.nameInput).value = '';
}

render() {
    return (
        <Form bsClass="col-xs-12" onSubmit={this.handleSubmit.bind(this)} >
            <FormGroup bsClass="form-group">
                <FormControl type="text" ref="nameInput" placeholder="Add New List" />
            </FormGroup>
        </Form>
    );
}

然后,我可以在 HandleSubmit 中拥有良好的 ID,但我不知道如何将其返回给 parent 组件..

感谢帮助

让父级 (TodosPage) 将函数作为 prop 传递给其子级 (ListForm)。然后onSubmit,让ListForm调用函数。

class TodosPage extends React.Component {
  handleListFormSubmit = (goodId) => {
    // do something with goodId
  }
  render() {
    return <ListForm onSubmit={this.handleListFormSubmit} />;
  }
}

class ListForm extends React.Component {
  handleSubmit = (event) => {
    // get GOOD ID from the form, then call the parent function
    // [...]
    this.props.onSubmit(goodId);
  }
  render() {
    <Form onSubmit={this.handleSubmit}>
      {/* form stuff here */}
    </Form>
  }
}

其实很简单,

我刚刚使用了我的 SelectList 函数,就像@Ty Le 说的那样通过 prop 将它发送到 child,但是要设置新状态,我必须添加我的 parent构造函数:

this.selectList = this.selectList.bind(this);

或者我得到一个错误:this.setState 未定义..

谢谢