![](/img/trans.png)
[英]React, how to access child's state from parent? no need to update parent's state
[英]React parent access state from child
如何在 React 中從父級內部的子級顯示狀態?
var Form = React.createClass({
render: function() {
return (
<form>
<h1>***CHILD STATE CHECKED***</h1>
{this.props.children}
</form>
)
}
})
var Checkbox = React.createClass({
getInitialState: function() {
return {
checked: true
}
},
toggle: function() {
this.setState({
checked: !this.state.checked
});
},
render: function() {
return (
<div onClick={this.toggle} aria-checked={this.state.checked} role="checkbox"></div>
);
}
})
ReactDOM.render(
<Form>
<Checkbox />
</Form>,
document.querySelector('#app')
);
在其父組件中(尤其是在父組件中的此標記內)顯示子組件狀態的最佳方式是什么? 如果沒有“丑陋的技巧”,這可能嗎?
當復選框被選中時,我想向表單添加一些節點或其他組件。
不要在復選框中調用切換。 將回調從 Form 類傳遞到 CheckBox 類。
在表單類中:
return(
<CheckBox onClick={this.onClick} />
)
onClick(){
console.log('Checkbox clicked');
}
在 CheckBox 類中:
<div onClick={this.props.onClick} aria-checked={this.state.checked} role="checkbox">
在父類中管理狀態,而不是在子類中。
盡管如果在父狀態中管理此 CheckBox 的狀態的答案是正確的,但在一些更復雜的情況下,您可能仍需要將狀態從子組件傳遞到組件:概念類似,您需要從parent to child ,它將像回調一樣使用,您將在其中處理該孩子的狀態:
var Form = React.createClass({
handleChildStateChange: function(newChildState) {
// handle the child state change here
}
render: function() {
const updatedChildren = React.Children.map(this.props.children,
(child) => {
return React.cloneElement(child, { updateParent: this.handleChildStateChange });
});
return (
<form>
<h1>***CHILD STATE CHECKED***</h1>
{updatedChildren}
</form>
)
}
})
然后,當更新子組件中的狀態時,以新狀態作為參數調用傳遞的函數(由於狀態的異步特性,我在這里使用函數式 setState ):
var Checkbox = React.createClass({
getInitialState: function() {
return {
checked: true
}
},
toggle: function() {
this.setState((state) => {
state.checked = !state.checked;
this.props.updateParent(state);
return state;
});
},
render: function() {
return (
<div onClick={this.toggle} aria-checked={this.state.checked} role="checkbox"></div>
);
}
})
最后,您使用的渲染保持不變:
ReactDOM.render(
<Form>
<Checkbox />
</Form>,
document.querySelector('#app')
);
如果您想了解更多關於將道具從孩子傳遞給父母的信息,這篇文章可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.