簡體   English   中英

通過道具動態傳遞React組件?

[英]Passing down React Components dynamically through props?

我正在尋找解決方案。 我有一個補充工具欄組件,需要根據父組件中的哪個按鈕被按下來呈現其他組件。 我不確定解決此問題或是否可能的最佳方法。 這是我的React代碼:

父組件

側邊欄組件上的內容道具需要根據單擊哪個Button組件傳遞不同的組件(因此第一個Button將傳遞內容道具中的組件,第二個Button傳遞組件等)。

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

謝謝

與其將組件作為道具傳遞,不如做這樣的事情

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM