How to pass props to {this.props.children}

后端 未结 26 3434
猫巷女王i
猫巷女王i 2020-11-21 23:42

I\'m trying to find the proper way to define some components which could be used in a generic way:


  
  

        
26条回答
  •  礼貌的吻别
    2020-11-22 00:31

    Method 1 - clone children

    const Parent = (props) => {
       const attributeToAddOrReplace= "Some Value"
       const childrenWithAdjustedProps = React.Children.map(props.children, child =>
          React.cloneElement(child, { attributeToAddOrReplace})
       );
    
       return 
    {childrenWithAdjustedProps }
    }

    Method 2 - use composable context

    Context allows you to pass a prop to a deep child component without explicitly passing it as a prop through the components in between.

    Context comes with drawbacks:

    1. Data doesn't flow in the regular way - via props.
    2. Using context creates a contract between the consumer and the provider. It might be more difficult to understand and replicate the requirements needed to reuse a component.

    Using a composable context

    export const Context = createContext(null);
    
    export const ComposableContext = ({ children, ...otherProps }:{children:ReactNode, [x:string]:any}) => {
        const context = useContext(Context)
        return(
          {children}
        );
    }
    
    function App() {
      return (
          
                 
                    
                
          
      );
    }
    
    const Provider1 =({children}:{children:ReactNode}) => (
        {children}
    )
    
    const Provider2 =({children}:{children:ReactNode}) => (
        {children}
    )
    
    const Displayer = () => {
      const context = useContext(Context);
      return 
    {context.greeting}, {context.name}
    ; };

提交回复
热议问题