reactjs - 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} />} />
);
两种方法都给出相同的结果,但我不知道引擎盖下发生了什么以及使用哪种方式。
解决方案
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)
}
}
推荐阅读
- android - 如何查看交易是用测试账户购买还是用真实账户购买?
- kotlin - Kotlin 协程比线程花费更长的时间
- javascript - React.js 中的自定义标题
- php - 在 mysql 中更新或插入每个用户的信息
- eclipse-rcp - 如何从 RCP 中的 IStatusLineManager 获取消息?
- python - 当两个输入之间有空格时如何输入?
- python - Keras - 如何让每一层在训练中花费的时间?
- github - 如何使用 splunk 监控 GitHub Appliance 实例
- install4j - ModifyTextFileAction 找不到并替换值
- java - Spring Boot批处理-启动时出现ClassNotFoundException