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

前端 未结 3 737
我在风中等你
我在风中等你 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:38

    In fact, React.cloneElement is not strictly associated with this.props.children.

    It's useful whenever you need to clone react elements(PropTypes.element) to add/override props, without wanting the parent to have knowledge about those component internals(e.g, attaching event handlers or assigning key/ref attributes).

    Also react elements are immutable.

    React.cloneElement( element, [props], [...children] ) is almost equivalent to: {children}


    However, the children prop in React is especially used for containment (aka composition), pairing with React.Children API and React.cloneElement, component that uses props.children can handle more logic(e.g., state transitions, events, DOM measurements etc) internally while yielding the rendering part to wherever it's used, React Router or compound component

    提交评论

提交回复
热议问题