[英]How do I reuse a React Component without having to change its inner props?
I don't know if that even exists. 我不知道那是否存在。 I am trying to reuse a component, however, the component I am trying to reuse receive props and already handles them inside of the component. 我正在尝试重用组件,但是,我正在重用的组件接收道具,并且已经在组件内部对其进行了处理。
If I reuse this component in another place I am going to have to change all of the props received. 如果我在其他地方重复使用此组件,则必须更改收到的所有道具。
Is that a common thing when developing in React or I am doing something wrong? 在React中开发时这是常见的事情还是我做错了什么?
I think you should divide the component with the props to two: 我认为您应该将带有道具的组件分成两个部分:
Component A. functionality (and all the props needed) 组件A.功能(以及所需的所有道具)
Component B. a type of container with no props just holding the component A 组件B。一种没有支撑道具A的容器
Hope this helps you! 希望这对您有所帮助!
Yes is common and is often resolved with HoC (High Order Components) 是,这很常见,通常可以通过HoC(高阶组件)解决。
ref: https://reactjs.org/docs/higher-order-components.html 参考: https : //reactjs.org/docs/higher-order-components.html
Example 例
function logProps(WrappedComponent) { return class extends React.Component { componentWillReceiveProps(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); } render() { // Wraps the input component in a container, without mutating it. Good! return <WrappedComponent {...this.props} />; } } } const EnhancedComponent = logProps(WrappedComponent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.