【问题标题】:Passing down React Components dynamically through props?通过 props 动态传递 React 组件?
【发布时间】:2019-06-08 00:36:55
【问题描述】:

我正在寻找解决方案。我有一个侧边栏组件,它需要根据按下父组件中的哪个按钮来呈现不同的组件。我不确定解决此问题的最佳方法,或者是否可能。这是我的 React 代码:

父组件

Sidebar 组件上的 content prop 需要根据被点击的 Button 组件传递不同的组件(所以第一个 Button 会在 content prop 中传递一个组件,第二个会传递一个组件等等)。

 return (
            <Fragment>
                <Sidebar
                    isOpen={this.state.menuOpen}
                    content={<Filters />}
                    />
                <PanelWrapper>
                    <IconContainer>
                       <Button />
                       <Button />
                    </IconContainer>
                </PanelWrapper>
              </Fragment>

)

子组件

这里将呈现内容道具:

class Sidebar extends Component {
    render() {
        return (
            <Menu
                customBurgerIcon={ false }
                noOverlay
                isOpen={this.props.isOpen}
            >
            {this.props.content}
            </Menu>
        )
    }
}

谢谢

【问题讨论】:

    标签: reactjs components react-props


    【解决方案1】:

    与其将组件作为道具传递,我可能会这样做

    class Sidebar extends Component {
        render() {
            return (
                <Menu
                    customBurgerIcon={ false }
                    noOverlay
                    isOpen={this.props.isOpen}
                >
                {switch(this.props.content) {
                    case("type1"): <mycomponent1 />
                    ...
                }}
                </Menu>
            )
        }
    }
    

    【讨论】:

    • 如果对您有用,请将其标记为已解决
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 2019-03-10
    • 2019-05-16
    • 2019-07-14
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多