从子组件

时间:2017-12-21 20:56:36

标签: reactjs

新的反应用户在这里。

我正在尝试从子表单访问父应用中的表单数据。我正在尝试提醒或控制来自父级的数据,以便我可以直观地看到表单中输入的内容。一旦我可以访问父级中的数据,我将尝试将其移动到我的列表数组。

PARENT

class App extends Component {

    constructor() {
    super();
    this.state = {
    lists: [], 
    items: {} 
    };
}

handleAddList(s) {
     alert('I am calling function from child')

     console.log(this.refs.id.value) // this errors out on me
}

 render() {
 return (
    <div className="App">
    <AddList addList={this.handleAddList.bind(this)} />
    <div id="listsDiv" className="List">
    <Lists lists={this.state.lists} items={this.state.items} addItem {this.handleAddItem.bind(this)} />
    </div>
    </div>
 );
 }

 }

class AddList extends Component {


handleSubmit(e) {
   e.preventDefault(); 
   alert(this.refs.id.value)

   this.props.addList()

}

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

2 个答案:

答案 0 :(得分:1)

您应该使用回调在输入上设置ref,如下所示:

<input type='text' ref={input => { this.input = input; }} id='newID'></input>

然后在您的事件处理程序中访问它:

alert(this.input.value);

但是,如果您不熟悉React,则在尝试使用ref之前应尝试使用受控组件。

https://reactjs.org/docs/forms.html

答案 1 :(得分:0)

import ReactDOM from 'react-dom';
class AddList extends Component {


handleSubmit(e) {
  e.preventDefault();
  var day = ReactDOM.findDOMNode(this.refs.id).value.trim();

  this.props.addList(day);

}

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

PARENT

class App extends Component {

handleAddList(args) {
   console.log(args);
}

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

稍微编辑一下,为你效劳。