gpt4 book ai didi

javascript - `React.createElement(...)` 和 `new MyComponent()` 有什么区别?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:30:43 24 4
gpt4 key购买 nike

简介:我对 React 有点困惑。我看过一些文章说 React 组件只是接收 props 并渲染到虚拟 DOM 的函数。然而,我看到的是它们是成熟的有状态怪物,我没有找到像函数一样对待它们的方法。

问题:为什么 React 组件的每次使用都包含在 React.createElement 中?为什么我不能改用 new MyComponent()?当我在 DevTools 中执行时,它看起来非常相似。既然组件是使用 React.createClass 创建的,为什么还需要 React.createElement?这对我来说似乎是多余的。

编辑:这看起来很相关:https://gist.github.com/sebmarkbage/ae327f2eda03bf165261

编辑 #2:这是相关的,但不是 React.Component vs React.createClass 的重复项,该问题询问有关创建类的问题。我不是在询问创建新的组件类,而是在询问创建该类的实例(元素)。

最佳答案

我想我found the answer here :

In React 0.12, we're making a core change to how React.createClass(...) and JSX works.

(...)

Currently var Button = React.createClass(...) does two things. It creates a class and a helper function to create ReactElements. It is essentially equivalent to this:

class ButtonClass { }

function ButtonFactory(...args) { return
React.createElement(ButtonClass, ...args); }

module.exports = ButtonFactory; ```

Then you access this in the consuming component by invoking the ButtonFactory.

var Button = require('Button');

class App { render() {
return Button({ prop: 'foo '}); // ReactElement
} }

Conceptually this is the wrong model. The source component should not be responsible for the output of App.

There are a few problems with this:

  • ES6 classes can't be directly exported, they need to be wrapped.
  • There's no convenient way to access the actual class and it's confusing which one you're using.
  • Static methods are wrapped in helpers that are not real function. As a convenience.
  • Auto-mocking destroys the factory so there is no way to test the result of render without disabling mocking.
  • Factories can be wrapped by other factories that returns something different than ReactElements. Making testing and optimizations impossible.
  • Languages with specialized features for object management have to defer to React instead of using the built-in features.

关于javascript - `React.createElement(...)` 和 `new MyComponent()` 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734046/

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