我正在学习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官方网站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} />} />
);
两种方法都能得出相同的结果,但是我不知道幕后情况和使用哪种方法。
答案 0 :(得分:2)
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)
}
}