如何从子组件的Form中获取数据并将其传递回Parent Componet?

时间:2017-11-24 11:51:08

标签: reactjs

我想将项目添加到lists.Items来自Child Component的表单。

class App extends Component {   
  constructor(props) {
    super(props);
    this.state = {
    lists: [],  // this holds the name of each list
      };
  }

  handleAddList(s) {
      this.setState({lists:s});
    };

  render() {
    return (
      <div className="App">
        <AddList addList={this.handleAddList.bind(this)} />
        </div>
    );
  }
}

我应该在handleSubmit函数中写什么,以便将列表返回到父组件?如何从表单元素访问输入的值?

class AddList extends Component {   

  handleSubmit(e) {
      e.preventDefault(); 
      this.props.addList(e.target.value);  //Isn't this the way to get input from Form ...//
  }

  render() {
    return (
      <div id="addListDiv">
      <form onSubmit={this.handleSubmit.bind(this)}>
      <div id='addList'>
      <label>What will be on your next list?&nbsp;
      <input type='text' ref='id' id='newID'></input>    //How ref is used?????
      </label>
      </div><br />
      <input type='submit' value='Create List' />
      </form>
      </div>
    );
  }
}
ReactDOM.render(
<App />,
document.getElementById('root'));

1 个答案:

答案 0 :(得分:0)

要通过参考访问您的输入值,您可以使用this.refs.id.value并将值从子组件传递到父组件,您可以使用道具。

let {Component} = React;

class App extends Component {   
  constructor(props) {
    super(props);
    this.state = {
        lists: [],  // this holds the name of each list
      };
    }

    handleAddList(s) {
      this.setState(prevState => {
      	return {lists: [s, ...prevState.lists]}
      });
    };

    render() {
      return (
        <div className="App">
          <AddList addList={this.handleAddList.bind(this)} />
          {this.state.lists.map((name, i) => <div key={i}>{name}</div>)}
        </div>
      );
    }
  }

class AddList extends Component {   
    handleSubmit(e) {
      e.preventDefault(); 
      let name = this.refs.id.value;
      if(name) {
      	this.refs.id.value = '';
        this.props.addList(name); 
      }
    }

    render() {
      return (
        <div id="addListDiv">
        <form onSubmit={this.handleSubmit.bind(this)}>
        <div id='addList'>
        <label>What will be on your next list?&nbsp;
        <input type='text' ref='id' id='newID'></input>   
        </label>
        </div><br />
        <input type='submit' value='Create List' />
        </form>
        </div>
      );
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
<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>