React.cloneElement vs 渲染道具模式

React.cloneElement vs render props pattern

我正在学习 React 并试图找出动态添加道具的最佳方式。我知道有两种方法可以做到这一点,但无法理解哪一种更好更快。

第一种方法是使用 React.cloneElement api

const Parent = ({ children }) => {
  const child = React.cloneElement(children, { newProp: 'some new prop' });

  return child;
};

const Child = ({ newProp }) => <div>{newProp}</div>;

const App = () => (
  <Parent>
    <Child />
  </Parent>
);

第二种方法是使用“render props”模式,在 React 官方网站上有描述:Render Props

const Parent = ({ render }) => {
  const newProp = 'some new prop';

  return render(newProp);
}

const Child = ({ newProp }) => <div>{newProp}</div>;

const App = () => (
  <Parent render={props => <Child newProp={props} />} />
);

两种方法都给出了相同的结果,但我不知道幕后发生了什么以及使用哪种方式。

React.cloneElement 是一个帮助程序,通常用于传递 inline-props 以避免污染代码。而不是像这样传递道具:

return <Child propA={myProps.propA} propB={myProps.propB} />

你可以这样做:

return React.cloneElement(Child, {...myProps})

这几乎是一样的:

 return <Child {...myProps} />

这里唯一的区别是 cloneElement 将保留以前附加的 refs

现在 renderPropsreuse stateful logic 的一种技术,其应用与 cloneElement 不同。第一个将帮助您进行 props 操作,第二个相当于 High Order Components 并且在您想要重用某些逻辑以动态地将道具注入 children:[=23= 时使用]

class Animation extends Component{
   state = {} 
   componentDidMount(){/*...*/}
   componentDidUpdate(){/*...*/}

   render(){
       const { customProps } = this.state
       const { children } = this.props

       return children(customProps)
   }
}