开门见山,在基于react类的组件中,prop
对象从何而来?
我正在遵循官方的React tic-tac-toe游戏教程。
首先,当我查看react Component
类(我们在创建React组件时对其进行扩展)的代码时,我观察到该函数有3个参数Component(props, context, updater)
,但我不明白为什么在调用props
()的情况下只像super(props)
这样传递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>
)
}
}
需要明确的是,我理解{this.props.value}
中的value
属性来自传递给Square
<Square value={index}/>;
的属性,该属性是另一个组件(在React教程中为Board
)中的子级,但这不是我所指的。
发布于 2019-06-23 06:11:07
属性是从超类传递到您在React中使用extends Components
创建的类的属性。
类似于OOPS中发生的事情,其中父类属性被传递给构造函数中的子类。类似地,在React中传递props的方式也适用于功能组件
注意-请不要将其与OOPS概念混淆,只是为了给出一个过于简化的版本
发布于 2019-06-23 07:51:39
有一件事是必要的:父类(即Component
类)的构造函数必须在任何React类组件中调用。
super
所做的(在Square
的constructor
中)是用Component
的props
调用Square
的构造函数(希望它不复杂)。
Square
有一个constructor
,那么你应该调用super
Square
没有构造函数,那么当使用<Square />
.时,Component
的构造函数将被自动调用
此外,您也不能在组件中直接使用context
或updater
。因此,没有必要在那里定义它们。
https://stackoverflow.com/questions/56721449
复制