开门见山,在基于 React 类的组件中,prop
在哪里?对象从何而来?
我正在关注 React 官方井字游戏教程。
首先,当我看一下 react Component
的代码时类(我们在创建 React 组件时扩展它)我观察到该函数有 3 个参数 Component(props, context, updater)
但我很困惑为什么在只调用 super() 的情况下 props
像这样传递super(props)
.
不应该为 context
传递值吗?和 updater
还?为什么不带super
运行代码没有报错被召唤?
import React, { Component } from "react";
export class Square extends Component
{
render()
{
return (
<span>
<button className="square" onClick={ () => { alert("click") } }>
{this.props.value}
</button>
</span>
)
}
}
明确地说,我知道 value
属性(property) {this.props.value}
来自传递给 Square
的属性<Square value={index}/>;
这是另一个组件中的子组件(在 React 教程中为 Board
),但这不是我所指的。
最佳答案
Props 是从 Super 类传递给您在 React 中使用 extends Components
创建的类的属性。
类似于 OOPS 中父类属性在构造函数中传递给子类的情况。在 React 中传递 props 的方式类似,这也适用于功能组件
Note - Please do not confuse it with OOPS concepts [ just to give a Oversimplified version]
关于javascript - 在 React 组件类中, "props"对象究竟是从哪里提取的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56721449/