簡體   English   中英

如何在 React 中將 props 傳遞給孩子的孩子?

[英]How to transfer props to children's children in React?

我正在將一些道具從布局轉移到每個孩子。 當孩子是直接布局的孩子時,這有效,但當我將布局的孩子包裝在例如 div 中時,它不起作用。

工作案例:

<Layout >
  <SectionA  language={props.language}  />
</Layout>

但在這種情況下不是這樣:

<Layout >
   <div>
     <SectionA  language={props.language}  />
   </div>
</Layout>

*當我在<SectionA />組件中訪問 props.language 時,它是未定義的

這是我將道具從布局轉移到其子級的方式

render(){

   const children = React.Children.map(this.props.children, (child, index) => {
        return React.cloneElement(child, {
            language: this.state.language,
        });
    });


 return (
        {children}
 )
    }

這似乎是 useContext 掛鈎的一個很好的案例。 這將允許您將語言作為上下文傳遞給上下文提供者的所有子代。 例如:

import React, { createContext, useContext } from 'react';

const LanguageContext = createContext();

const LanguageProvider = (props) => {
    // Can set up state here if needed
    return (
        <LanguageContext.Provider value={'defaultLanguage'}>
            {props.children}
        </LanguageContext.Provider>
    );

// Wrap the components that need access to the context in the provider
const App = () => {
    return (
        <LanguageProvider>
            <Layout >
                <div>
                    <SectionA />
                </div>
             </Layout>
        </LanguageProvider>
    );

}


// And to access that context in SectionA (or any other child)
const SectionA = () => {
    const language = useContext(LanguageContext);

    return (<h1>Language is {language}</h1>);
}

我很確定有更好的方法來做到這一點(可能在布局文件中),但這是我解決這個問題的方法:

首先,我使用了第二個 hoc 來包裝 sectionA 組件並為其設置樣式:

function simpleWrapper(props) {


return(
    <React.Fragment>
    <div className='container'>
      <SectionA language={props.language}/>  
    </div>
    <div>
      <SectionB language={props.language}/>  
    </div>
     ...
    <style jsx>{`
      .container {
        Stuff
    `}</style>
    </React.Fragment>
)
}

export default simpleWrapper;

然后我將所有道具轉移到這個包裝器:

<Layout >
  <SimpleWrapper language={props.language} />

</Layout>

)

請注意,我使用這種方法是因為我有不止一個組件

暫無
暫無

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

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