[英]In REACT.js how can I pass a state from child component up to Parent component as a prop
[英]How can I pass a prop by child index in React
我正在嘗試為React開發一個通用容器,它的工作原理如下:
<PanelContainer>
<PanelConsole />
<PanelMemory />
<PanelLog />
</PanelContainer>
我想在容器中動態創建一個標簽系統,其工作方式如下:
renderTabs = () => {
return (
<ul className="panel_tabs">
{React.Children.map(this.props.children, (child, i) =>
<li key={child.type.display_name} onClick={() => this.handleClickTab(i)}>
{child.type.display_name}
</li>
)}
</ul>
);
}
這允許我使用類中的display_name屬性呈現選項卡。 到目前為止這是有效的,但現在我正試圖讓點擊工作。 我希望它能夠動態工作,所以我不必為每個面板實例構建專門的容器。 理想情況下,我希望通過索引在this.props.children中設置子屬性,例如:
this.props.children[0].props.shown = false;
這可能嗎?
我認為React.Children.map
和React.cloneElement
適合您:
render() {
const { children } = this.props;
const tabs = this._renderTabs();
const childrenWithProps = React.Children.map(children, (child, id) =>
React.cloneElement(child, { shown: this.state.shows[i] }));
return (
<div>
<div>{tabs}</div>
<div>{childrenWithProps}</div>
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.