我正在从这个site学习高阶组件,但不明白 this
在其中如何工作。看看下面的内容,构造函数中的 this
是否指的是返回的内容,如最终结果组件中那样?而 {...this.props}
中的 this
是 Connect
组件? 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/