简体   繁体   中英

How can I pass a prop by child index in React

I'm trying to develop a generic container for React, that would work like this:

<PanelContainer>
    <PanelConsole />
    <PanelMemory />
    <PanelLog />
</PanelContainer>

I want to dynamically create a tab system within the container, this works as follows:

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>
        );
    }

This allows me to render the tabs with the display_name property within the class. This so far works, but now I'm trying to get the click to work. I want it to work dynamically so I don't have to build specialized containers for each instance of the panel. I'd ideally like to set the property of a child in this.props.children by index, so for example:

this.props.children[0].props.shown = false;

Is this possible?

I think React.Children.map and React.cloneElement works for you:

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>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM