gpt4 book ai didi

javascript - React 中的匿名类

转载 作者:行者123 更新时间:2023-11-29 10:29:08 25 4
gpt4 key购买 nike

我听说过匿名函数,但匿名类的概念对我来说是新的。例如,我们这里有一个 HOC,看起来像这样。

import React, { Component } from 'react';

const withClass = (WrappedComponent, className) => {
return class extends Component {
render () {
return (
<div className={className}>
<WrappedComponent {...this.props} />
</div>
)
}
}
}

[问题]在这里,我无法理解这行 return class extends Component { 的含义(我知道来自 React 的 extends 组件,{component})

有人可以向我解释一下它的一般作用吗?如果描述非常模糊或简短,请告诉我。

最佳答案

Here, I am unable to understand meaning of this line return class extends Component {

Can someone explain me what it does generally?

它定义了一个没有名称的类,并从 withClass 函数返回它。

也就是说,它执行此操作,但全部在一个表达式中并且没有给类命名:

import React, { Component } from 'react';

const withClass = (WrappedComponent, className) => {
class TheClass extends Component {
render () {
return (
<div className={className}>
<WrappedComponent {...this.props} />
</div>
)
}
}
return TheClass;
}

你可以这样使用它:

const MyClass = withClass(SomeComponent, "foo");

...然后您可以像这样使用它:

<MyClass foo="bar"/>

...你会得到

<div className="foo">
<SomeComponent foo="bar" />
</div>

...渲染时。

关于javascript - React 中的匿名类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com