从子组件React传递参数

Ram*_*gov 4 javascript reactjs

我尝试将参数从子组件传递给父组件.下面的PS片段无法解决,如果有人解决这个问题,它会非常棒.

class Parent extends React.Component {

  suggestionClick(id) {
    console.log(this.props, id); // {props Object} , undefined
  }

  render(){
    return (
      <ChildComponent click={this.suggestionClick.bind(this)} />
    );
  }
}


const ChildComponent = ({ click }) => (
  <SubChildComponent id="1" click={() => click()} />
);

const SubChildComponent = ({ click, id }) => (
  <div className="subsubcomponent" click={() => click(id)} />
);



ReactDOM.render(
  <Parent />,
  document.getElementById('app')
);
Run Code Online (Sandbox Code Playgroud)
<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="app"></div>
Run Code Online (Sandbox Code Playgroud)

Joã*_*nha 6

  1. 不要使用div来触发点击.正确的方法是使用一个按钮例如
  2. 正确的函数处理程序是onClick而不仅仅是单击

class Parent extends React.Component {

  suggestionClick(id) {
    alert(id);
    console.log(this.props, id); // {props Object} , undefined
  }

  render(){
    return (
      <ChildComponent click={this.suggestionClick.bind(this)} />
    );
  }
}


const ChildComponent = ({ click }) => (
  <SubChildComponent id="1" click={click} />
);

const SubChildComponent = ({ click, id }) => (
  <button className="subsubcomponent" onClick={() => click(id)}>click me</button>
);



ReactDOM.render(
  <Parent />,
  document.getElementById('app')
);
Run Code Online (Sandbox Code Playgroud)
<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="app"></div>
Run Code Online (Sandbox Code Playgroud)