反应 HOC 中的 @ 是什么?

what is @ in react HOC?

index.jsx

import React from 'react'
import { render } from 'react-dom'

import Main from './Main'

window.DatoCmsPlugin.init((plugin) => {
  plugin.startAutoResizer()

  const container = document.createElement('div')
  document.body.appendChild(container)

  render(<Main plugin={plugin} />, container)
})

Main.jsx

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import connectToDatoCms from './connectToDatoCms';
import './style.sass';

@connectToDatoCms(plugin => ({
  developmentMode: plugin.parameters.global.developmentMode,
  fieldValue: plugin.getFieldValue(plugin.fieldPath),
}))

export default class Main extends Component {
  static propTypes = {
    fieldValue: PropTypes.bool.isRequired,
  }

  render() {
    const { fieldValue } = this.props;

    return (
      <div className="container">
        {JSON.stringify(fieldValue)}
      </div>
    );
  }
}

connectToDatoCms.jsx

import React, { Component } from 'react'

export default mapPluginToProps => BaseComponent => (
  class ConnectToDatoCms extends Component {
    constructor (props) {
      super(props)
      this.state = mapPluginToProps(props.plugin)
    }

    componentDidMount () {
      const { plugin } = this.props

      this.unsubscribe = plugin.addFieldChangeListener(plugin.fieldPath, () => {
        this.setState(mapPluginToProps(plugin))
      })
    }

    componentWillUnmount () {
      this.unsubscribe()
    }

    render () {
      return <BaseComponent {...this.props} {...this.state} />
    }
  }
)

我使用此命令为 datoCMS 插件生成了起始代码,npx -p yo -p generator-datocms-plugin -c 'yo datocms-plugin'

@connectToDatoCms、Main.jsx中的@是什么。

@connectToDatoCms 使用装饰器模式。

您代码中的 webpack 配置设置为处理装饰器,可能使用 babel-plugin-transform-decorators

装饰器类似于 HOC

Decorators 只是一个函数的包装器。它们用于在不修改底层功能的情况下增强功能的功能。

使用当前的 HOC 语法模式,上面的内容可以用作

import connectToDatoCms from './connectToDatoCms';
import './style.sass';

class Main extends Component {
  static propTypes = {
    fieldValue: PropTypes.bool.isRequired,
  }

  render() {
    const { fieldValue } = this.props;

    return (
      <div className="container">
        {JSON.stringify(fieldValue)}
      </div>
    );
  }
}
const mapPluginToProps = plugin => ({
    developmentMode: plugin.parameters.global.developmentMode,
    fieldValue: plugin.getFieldValue(plugin.fieldPath),
 })
export default connectToDatoCms(mapPluginToProps)(Main);