javascript - 在 React 中将数据传递给父级

标签 javascript reactjs dom

我是 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>

    );
  }

}

这是我的子组件,

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

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

最佳答案

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

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

这可以防止将您的组件耦合在一起,并且可以简化以后的测试。

关于javascript - 在 React 中将数据传递给父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40514057/

相关文章:

javascript - 删除特定分隔符后面的字符串的最后部分

javascript - ReactNative - 在 ListView 中点击行给出错误 : Cannot read property `_pressRow` of null

javascript - 在 React Native 应用程序中将语言更改为用户首选项

javascript - 浏览器如何识别DOM节点?

javascript - jQuery : Split the DOM Node using jQuery

javascript - 载回原始 div 内容

javascript - 更改 Algolia instantsearch.js 统计模板

javascript - 为什么我的 JS 不添加 HTML 类?

javascript - 不打印控制台日志

javascript - 尝试映射我的 Prop 时,我收到 Cannot read property of 'exercises' of undefined 错误