![](/img/trans.png)
[英]How to pass Parent props to Children, when rendering using this.props.children() and React.cloneElement?
[英]Pass parent function to child when using this.props.children
class Parent extends React.Component {
foo() {
console.log('i was called');
}
render() {
return(
this.props.childen;
);
}
}
class Child extends React.Component {
render() {
return(
<div onClick="call foo here">Child</div>
);
}
}
React.render(<Parent><Child></Parent>, document.getElementById('View'));
我試圖像最后一行所示渲染出Child。 在這種情況下,如何將foo()
從父級傳遞給子級?
我通常知道在Parent的渲染中我們執行<Child func={this.foo} />
您可以在Parent的render方法中調用Child,然后將其作為函數傳遞給foo。 然后在子組件上,您可以將其作為道具進行檢索。
class Parent extends React.Component {
foo() {
console.log('i was called');
}
render() {
return(
<Child foo={this.foo} />
);
}
}
class Child extends React.Component {
render() {
return(
<div onClick={this.props.foo}>Child</div>
);
}
}
React.render(<Parent />, document.getElementById('View'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.