【问题标题】:How to transfer props to children's children in React?如何在 React 中将 props 传递给孩子的孩子?
【发布时间】:2022-01-02 18:17:03
【问题描述】:

我正在将布局中的一些道具转移给每个孩子。这在子元素是直接布局的子元素时有效,但当我将布局的子元素包装在例如 div 中时它不起作用。

工作案例:

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

但在这种情况下并非如此:

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

*当我访问 &lt;SectionA /&gt; 组件中的 props.language 时,它​​是未定义的

这是我将道具从布局转移到其子级的方式

render(){

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


 return (
        {children}
 )
    }

【问题讨论】:

  • 如果我理解您正在尝试正确执行的操作,您正在尝试向 Layout 的子项添加一个道具,在您的第二个示例中是 div 元素,而不是 Section 组件。
  • 我正在尝试向 SectionA 组件添加一个道具,该组件位于第二个示例中的 div 内部。我用 div 包装 SectionA 以进行样式设置

标签: javascript reactjs next.js


【解决方案1】:

这似乎是 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>);
}

【讨论】:

    【解决方案2】:

    我很确定有更好的方法来做到这一点(可能在布局文件中),但这是我解决这个问题的方法:

    首先,我使用了第二个 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>
    

    )

    请注意,我使用这种方法是因为我在

    内部有不止一个组件

    【讨论】:

      猜你喜欢
      • 2020-04-10
      • 2021-08-20
      • 2018-06-29
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      相关资源
      最近更新 更多