When should I be using React.cloneElement vs this.props.children?

前端 未结 3 745
我在风中等你
我在风中等你 2020-12-12 11:10

I am still a noob at React and in many examples on the internet, I see this variation in rendering child elements which I find confusing. Normally I see this:



        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 11:50

    props.children isn't the actual children; It is the descriptor of the children. So you don't have actually anything to change; you can't change any props, or edit any functionality; you can only read from it. If you need to make any modifications you have to create new elements using React.CloneElement.

    https://egghead.io/lessons/react-use-react-cloneelement-to-extend-functionality-of-children-components

    An example:

    main render function of a component such as App.js:

    render() {   
        return(
                
                  First
                  Second
                  Third
                   
        ) 
    }
    

    now let's say you need to add an onClick to each child of Paragraph; so in your Paragraph.js you can do:

    render() {
            return (
              
    {React.Children.map(this.props.children, child => { return React.cloneElement(child, { onClick: this.props.onClick }) })}
    ) }

    then simply you can do this:

    render() {   
      return(
            
              First
              Second
              Third
               
       ) 
    }
    

    Note: the React.Children.map function will only see the top level elements, it does not see any of the things that those elements render; meaning that you are providing the direct props to children (here the elements). If you need the props to be passed down further, let's say you will have a

    inside one of the elements that wants to use the onClick prop then in that case you can use the Context API to do it. Make the Paragraph the provider and the Sentence elements as consumer.

提交回复
热议问题