首页 > 解决方案 > React.cloneElement 与渲染道具模式

问题描述

我正在学习 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>
);

第二种方法是使用“渲染道具”模式,在 React 官方网站上描述:渲染道具

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} />} />
);

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

标签: reactjsreact-props

解决方案


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

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

你可以这样做:

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

这几乎与以下内容相同:

 return <Child {...myProps} />

这里唯一的区别是cloneElement会保留之前附加refs的 .

现在renderProps是一种技术,reuse stateful logic并且具有与cloneElement. 第一个将帮助您进行props操作,第二个等效于High Order Components并且在您想要重用某些逻辑以动态地将道具注入您的孩子时使用:

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

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

       return children(customProps)
   }
}

推荐阅读