gpt4 book ai didi

javascript - 我如何在 React 中通过子索引传递 Prop

转载 作者:行者123 更新时间:2023-11-29 15:13:41 24 4
gpt4 key购买 nike

我正在尝试为 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.mapReact.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>
)
}

关于javascript - 我如何在 React 中通过子索引传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com