简体   繁体   English

如何重用React组件而无需更改其内部道具?

[英]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.

相关问题 如何测试在其父级上调用函数的 React 组件,这会更改组件上的 props? - How do I test a React component that calls a function on its parent, which changes props on the component? 如何将道具传递到反应组件? - How do I pass props to a react component? 根据道具更改react组件的样式 - Change the style of the react component based on its props 我如何渲染作为带有附加道具的道具传入的反应组件? - How do i render a react component passed in as a props with additional props? 为什么我的React孙子组件在收到其父组件的道具更改后没有更新? 或者:我需要使用状态吗? - Why does my React grandchild component not update after receiving a change in props from its parent? Or: do I need to use state? React memoized 组件重新渲染而不改变道具 - React memoized component rerenders without props change 如何使用 props 更改 React 组件的颜色 - How do you change the color of a React component using props 我如何重用反应组件但具有不同的颜色? - how do i reuse a react component but with different colours? 如何在React中不带道具的情况下将数据传递给组件? - How can I pass data to a component without props in React? 如何在单个组件中渲染多个道具,然后将这些道具传递给 React 中的子组件 - How do i render multiple props in a single component and then pass those props to a child component in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM