javascript - `this` 在高阶组件中如何工作?

标签 javascript reactjs ecmascript-6 components higher-order-functions

我正在从这个site学习高阶组件,但不明白 this 在其中如何工作。看看下面的内容,构造函数中的 this 是否指的是返回的内容,如最终结果组件中那样?而 {...this.props} 中的 thisConnect 组件? this 这里怎么能指代两个不同的东西呢?

无状态组件

const Greeting = ({ name }) => {
  if (!name) { return <div>Connecting...</div> }

  return <div>Hi {name}!</div>
}

高阶组件

const Connect = ComposedComponent =>
  class extends React.Component {
    constructor() {
      super()
      this.state = { name: "" }
    }

componentDidMount() {
  // this would fetch or connect to a store
  this.setState({ name: "Michael" })
}

render() {
  return (
    <ComposedComponent
      {...this.props}
      name={this.state.name}
    />
  )
}

}

最佳答案

is the this in the constructor referring to what's being returned, as in the final resulting component? And the this that is in {...this.props} is the Connect component?

Connect 是一个函数,而不是一个组件。
Connect 是一个接收CompositedComponent 并返回一个新组件的函数。 this 引用用于返回的(父)组件。在构造函数中,它初始化该组件的状态,并在 render 中将其属性传递给 CompositedComponent

关于javascript - `this` 在高阶组件中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40227026/

相关文章:

javascript - Angular js等待服务调用返回

ReactJs:在没有 JSX 的情况下设置元素的数据属性

reactjs - 如何在单个组件上设置背景图像?

javascript - KendoUI 和纯 Javascript(无 jQuery)

javascript - 如果 localStorage 为 null,则从 json 文件设置

Javascript:向不同大小的数组添加 0 值

javascript - 为了相互对应Mithril的多个输入?

javascript - 在 React 中设置状态的多个 Fe​​tch 请求

javascript - 为什么 Array#map 不返回正确的数组?

ecmascript-6 - 转译 node-fetch require 返回错误