gpt4 book ai didi

reactjs - 和 Component() 的区别

转载 作者:行者123 更新时间:2023-12-04 15:45:22 30 4
gpt4 key购买 nike

我已经明白了Difference between React Component and React Element , 使用 JSX 基本上调用 React.createElement它返回一个元素,例如:

const element = <Component />

但是,当我将组件作为函数调用时会发生什么?
const whoAmI = Component()

我在多个开发人员的代码中看到了类似于以下(过于简化)的 2 种方法:
class Big extends React.PureComponent {
renderSomething() { return <div>something</div> }
render() {
const helper = () => <div>{x}</div>
return <>
{this.renderSomething()}
{helper()}

<this.renderSomething />
<helper />
</>
}
}

这些是相同的还是有什么区别?

最佳答案

创建的元素数量有所不同:

  • <Fn />创建一个中间元素,“Fn”本身
    (即它安装并呈现“Fn”组件)
  • Fn()只使用名为“Fn”的函数的返回值
    (“Fn”实际上不是一个 React 组件,只是一个返回 React 元素的函数)

  • 这可以在 React Developer Tools 中看到,类似于以下内容:
    <Big>
    <div>something</div>
    <div>1</div>
    <this.renderSomething>
    <div>something</div>
    <this.renderSomething>
    <helper>
    <div>2</div>
    <helper>
    </Big>

    有关 React 工作原理的更多详细信息: https://overreacted.io/react-as-a-ui-runtime/ .

    关于reactjs - <Component/> 和 Component() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55994365/

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