在 React 高阶组件中传播 props 的目的是什么?

What is the purpose of spreading props in React Higher Order Components?

我试图了解 React 的高阶组件结构,但所有资源都假设您在编写时已经了解展开运算符在高阶组件中的用途: 基础组件 {...this.props} {...this.state} 。如果组件已经作为道具传入,为什么有必要像这样展开道具?

import React, { Component } from 'react';

const EnhanceComponent = BaseComponent => {
    return class EnhancedComponent extends Component {
        state = {
            name: 'You have been enhanced'
        }
        render() {
           return ( 
           <BaseComponent {...this.props} {...this.state} />   
        )
       }
    }
};

export default EnhanceComponent;

答案直接在docs中解释:

Convention: Pass Unrelated Props Through to the Wrapped Component HOCs add features to a component. They shouldn’t drastically alter its contract. It’s expected that the component returned from a HOC has a similar interface to the wrapped component.

HOCs should pass through props that are unrelated to its specific concern. Most HOCs contain a render method that looks something like this:

要理解这一点,您应该知道 {...this.props} 的作用。在你的情况下

const EnhanceComponent = BaseComponent => {
    return class EnhancedComponent extends Component {
        state = {
            name: 'You have been enhanced'
        }
        render() {
           return ( 
           <BaseComponent {...this.props} {...this.state} />   
        )
       }
    }
};

export default EnhanceComponent;

EnhanceComponent HOC 做了一个简单的操作,为当前正在渲染的组件添加状态名称,所以本质上当你使用这个 HOC 时,你应该能够将你的原始组件所需的道具直接传递给它而不是消耗它们在 HOC 中,这就是 {...this.props} 传播语法的用途。您可以阅读此答案以了解有关如何 ... works

的更多详细信息

考虑像这样使用的简单组件的情况

<MyComponent className='wrapper-container' onClick={this.handleClick} />

并定义为

class MyComponent extends React.Component {
      render() {
         const { className, onClick} = this.props;

         ...
      }
   }

现在,如果您在此组件上使用 HOC,例如

const EnhancedMyComponent = EnhanceComponent(MyComponent);

你会把它渲染成

<EnhancedMyComponent className='wrapper-container' onClick={this.handleClick} />

现在如果你不在你的 HOC 中写 {...this.props},那么 MyComponent 将不再有 classNameonClick 作为 props

例如,您有一个组件并且想要增强它:

const Message = props => (
  <div className={props.type}>
    <p>{props.message}</p>
  </div>
)

const EnhancedMessage = enhance(Message);

然后你可以在代码中的某处使用增强组件:

<EnhancedMessage type="alert" message="Something went wrong" />

如果你不传播传递给 HOC 的道具,Message 组件如何知道传递的道具?

简单的回答:

传播道具不是强制性的

如果你想保留一个组件的 props,在包装后保留在那里,然后在 wrapper 组件中传播 props 否则不要传播它。