什么是类在React中扩展React.component [英] what is class extends React.component in React
问题描述
在此链接中 https://reactjs.org/docs/higher-order-components.html 其中的解释是高阶组件.下面的代码具有扩展React.component的类.此类关键字在这里是什么?
In this link https://reactjs.org/docs/higher-order-components.html where explanation is of higher order component.The code is below has class extends React.component. What is this class keyword here?
function logProps(WrappedComponent) {
return class extends React.Component {
componentDidUpdate(prevProps) {
console.log('Current props: ', this.props);
console.log('Previous props: ', prevProps);
}
render() {
// Wraps the input component in a container, without mutating it. Good!
return <WrappedComponent {...this.props} />;
}
}
}
推荐答案
The above code is creating an unnamed / anonymous class by extending React.Component
class, hence, creating a new React Component which wraps (returns) the WrappedComponent
passed to the function logProps
.
类表达式的语法为:
const MyClass = class [className] [extends otherClassName] {
// class body
};
其中的名称 className
(以及 extended otherClassName
)是可选的.
where the name className
(and also, extends otherClassName
) is optional.
而且,在您所讨论的代码中,它只是返回结果,而不是将其分配给变量:
And, in your code in question, it is just returning the result instead of assigning it to a variable:
return class [className] [extends otherClassName] {
// class body
};
请注意,有两种方式可以创建反应组件,一种是通过编写函数
,而另一种是通过编写 class
.
Note that, there are two ways to create a React Component, one is by writing a function
and the other is by writing a class
.
并且,在JavaScript中,类是在ECMAScript 2015(也称为ES6)中引入.
And, in JavaScript, classes was introduced in ECMAScript 2015 (also knows as ES6).
这篇关于什么是类在React中扩展React.component的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!