组件之间的关系

时间:2018-12-18 21:32:17

标签: javascript reactjs

我有两个有状态组件:Grid和Item。Item由Grid渲染,并且具有引用Grid <Item example={this.props.inGridHandler} />中定义的方法(处理程序)的props 好。但是,如果我有第三个有状态组件,将其命名为Handy,并且希望inGridHandler不在像以前那样在Grid组件中定义,而是在Handy中定义。如何通过保留所有这些结构来实现这一目标?

class Grid extends Component{

ingridHandler=()=>{
console.log('I want to be  defined in Handy Component, not here');
}

Render(){
Return(
`<Item example={this.inGridHandler} />`
);

}
};
export default Grid;




class Handy extends Component{

inGridHandlerWantToBeDefinedHere=()=>{
console.log("I want to be defined here and pass to Grid component as props of Item component which is rendered there'
}

render(){

return(

)
}


}

1 个答案:

答案 0 :(得分:1)

如果我理解正确的话,这就是您想要的。这是一个非常简单的过程。您只是将道具一直向下传递。但是,正如我以后尝试在评论中解释的那样,如果您不想通过这样的道具,您应该考虑更好的方法。

class Handy extends React.Component {
  inGridHandler = () => {
    console.log("ingridhandler");
  };

  render() {
    return <Grid inGridHandler={this.inGridHandler} />;
  }
}

class Grid extends React.Component {
  render() {
    return <Item inGridHandler={this.props.inGridHandler} />;
  }
}

const Item = props => (
  <button onClick={props.inGridHandler}>Click me and look the console.</button>
);

ReactDOM.render(
  <Handy />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>