之间的区别和组件

之间的区别和组件

本文介绍了<组件/>之间的区别和组件()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经理解了React Component 和 React Element 之间的区别,使用 JSX 基本上调用了 React.createElement 返回一个元素,例如:

const element = 

但是,当我将组件作为函数调用时会发生什么?

const whoAmI = Component()

我在多个开发人员的代码中看到了类似于以下(过于简化)的 2 种方法:

class Big extends React.PureComponent {renderSomething() { return <div>something</div>}使成为() {const helper = () =><div>{x}</div>返回 <>{this.renderSomething()}{帮手()}<this.renderSomething/><帮手/></>}}

这些是相同的还是有什么不同?

解决方案

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

  • 创建一个中间元素,即Fn"本身
    (即它安装并呈现Fn"组件)

  • Fn() 只是使用名为Fn"的函数的返回值
    (Fn"实际上不是一个 React 组件,只是一个返回 React 元素的函数)

这可以在 React 开发者工具中看到,类似于以下内容:

<

东西
1

<this.renderSomething

东西

<this.renderSomething<帮手

2

<帮手</

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

I already understand the Difference between React Component and React Element, that using JSX basically calls React.createElement which returns an element, e.g.:

const element = <Component />

However, what happens when I call a Component as a function?

const whoAmI = Component()

I have seen the 2 approaches in code from multiple developers similar to following (oversimplified):

class Big extends React.PureComponent {
  renderSomething() { return <div>something</div> }
  render() {
    const helper = () => <div>{x}</div>
    return <>
      {this.renderSomething()}
      {helper()}

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

Are these identical or what's the difference?

解决方案

There is a difference in number of elements created:

  • <Fn /> creates an intermediate element, the "Fn" itself
    (i.e. it mounts and renders the "Fn" Component)

  • Fn() just uses the return value of the function called "Fn"
    ("Fn" is not actually a React Component, just a function that returns a React Element)

This can be visible in the React Developer Tools, similar to following:

<Big> <div>something</div> <div>1</div> <this.renderSomething> <div>something</div> <this.renderSomething> <helper> <div>2</div> <helper></Big>

For more details on how React works: https://overreacted.io/react-as-a-ui-runtime/.

这篇关于&lt;组件/&gt;之间的区别和组件()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:31