簡體   English   中英

ReactJS,將prop從父組件傳遞到子組件?

[英]ReactJS, passing prop from parent to child component?

我有一堆需要相同道具的組件,並且逐一添加JSX很麻煩,我可以在父級中創建一塊JSX並將其作為道具傳遞給這些子組件嗎?

這基本上是我想做的:

function App(props) {
    /*not part of the actual code, but I want to 
    pass this h1 tag into the  bottom components as a prop*/
    <h1>{props.heading}</h1> 
    <Home heading="Home"/>
    <AboutMe heading="About Me"/>
    <Contact heading="Contact"/>
}

我知道上面的代碼不是您應該怎么做,但是有沒有辦法我可以完成該功能?

是的,那是可能的。 只需將JSX組件分配給一個變量,然后將該變量作為prop傳遞即可。 你有正確的主意。 例如:

var customHeader = <h1>Here's a custom component</h1>

您也可以將customHeader設置為React組件,例如: var customHeader = <CustomHeader />

您可以通過<MyComponent header={customHeader}/>進行傳遞,並在MyComponent頁面的render函數中,只需使用{this.props.header}即可加載組件。 可以對任意數量的組件重復此操作。

根據評論進行編輯。 在那種情況下,我會將組件包裝在一個函數中。 例如:

getCustomHeader = (title) => {
    return <MyHeader
        headerTitle={title}
    />
}

現在,在渲染函數中,可以調用getCustomHeader

render() {
    return <div>
        <MyComponent1 header={this.getCustomHeader("Title A")} />
        <MyComponent2 header={this.getCustomHeader("Title B")} />
    </div>
}

暫無
暫無

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

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