在React中将数据传递给父级

4 javascript dom reactjs

我是React的新手,因此是个问题.我有一个父组件 - HomePage与子组件 - SideBar.

我的子组件侧边栏需要在提交按钮单击上将数据传递回父级,父级需要在api上发布该按钮.

这是我的父组件,

class HomePage extends React.Component{

  constructor(props) {
    .......
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(){
  //Logic to get the data from the child and post to localhost:8080/
  }
  render(){
    return(

        <div className="col-md-2 left-pane">
          <Sidebar handleSubmitButton={this.state.handleSubmit}/>
        </div>

    );
  }

}
Run Code Online (Sandbox Code Playgroud)

这是我的孩子组成部分,

class Sidebar extends React.Component {

  handleSubmitButton(event) {
    event.preventDefault();

  }

  render() {
    return (
      <div>

          <input type="text"/>

            <button type="button" className="btn btn-info btn-icons" onClick={this.props.handleSubmitButton} >
              <span className="glyphicon glyphicon-send" aria-hidden="true"/>
            </button>


      </div>
    );

  }
}

Sidebar.propTypes = {
  handleSubmitButton: React.PropTypes.func
};
Run Code Online (Sandbox Code Playgroud)

我的问题是如何使用侧边栏按钮上的onclick方法获取输入文本并将其传递给父级以将其发布到api上.任何帮助赞赏.

Ash*_*son 5

您的父组件不应直接访问输入,而是依赖子组件在需要时将任何值传递给父组件.

class HomePage extends React.Component {

  constructor(props) {
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(textInputValue){
    // The callback passed to the child component will
    // submit the data back to it's parent.
    // Logic to post to localhost:8080/
  }

  render(){
    return(
      <div className="col-md-2 left-pane">
        <Sidebar handleSubmitButton={ this.handleSubmit }/>
      </div>
    );
  }
}

class Sidebar extends React.Component {

  constructor(props) {
    this.handleSubmitButton = this.handleSubmitButton.bind(this);
  }

  handleSubmitButton(event) {
    event.preventDefault();

    // By giving the input the `ref` attribute, we can access it anywhere
    const textInputValue = this.refs.input.value;

    // Submit the value to the parent component
    this.props.handleSubmitButton(textInputValue);
  }

  render() {
    return (
      <div>
        <input type="text" ref="input" />

        <button type="button" className="..." onClick={this.handleSubmitButton} >
          <span className="glyphicon glyphicon-send" aria-hidden="true"/>
        </button>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这可以防止将组件耦合在一起,以便以后进行测试.


小智 3

在您的子组件中,您可以为 ref 属性创建一个属性。直接访问 DOM 元素通常是通过设置 refs 来完成的。

在父组件中,您可以使用带有回调的箭头函数,该函数允许您<input>通过简单地键入 this.textInput 来访问父组件中任何位置的 DOM 元素

有关 refs 的更多信息可以在 React 官方文档中找到:https://facebook.github.io/react/docs/refs-and-the-dom.html

父组件:

handleSubmit() {
  console.log(this.textInput.value);
}

<Sidebar 
  inputRef={(input) => this.textInput = input} 
  handleSubmitButton={this.state.handleSubmit}
/>
Run Code Online (Sandbox Code Playgroud)

子组件:

<input ref={this.props.inputRef} type="text"/>
Run Code Online (Sandbox Code Playgroud)