gpt4 book ai didi

reactjs - React.Component 与 React.createClass

转载 作者:行者123 更新时间:2023-12-03 12:56:53 25 4
gpt4 key购买 nike

我很困惑组件和 react 类之间有什么区别?

什么时候我应该在 React 类上使用组件?看起来组件就是一个类,而 createClass 创建了一个组件。

https://facebook.github.io/react/docs/top-level-api.html

React.Component

This is the base class for React Components when they're defined using ES6 classes. See Reusable Components for how to use ES6 classes with React. For what methods are actually provided by the base class, see the Component API.

React.createClass

Create a component class, given a specification. A component implements a render method which returns one single child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.

最佳答案

MyComponent extends React.Component 唯一不支持的 React.createClass 功能是 mixins。

要做getInitialState(),你可以这样做:

class MyComponent extends React.Component {
constructor(props, context) {
super(props, context);

// initial state
this.state = {
counter: 0
};
}

...
}

或者如果你使用像 babel 这样的转译器,你可以得到

class MyComponent extends React.Component {
state = {
counter: 0
}

...
}

您可以像上面所示那样使用 .bind(this) 显式绑定(bind),或者使用粗箭头 ES6 语法,而不是 createClass 提供的自动绑定(bind):

class MyComponent extends React.Component {
onClick = () => {
// do something
}
...
}

您可以将内容放入构造函数中,而不是将内容放入 componentWillMount 中,如下所示:

class MyComponent extends React.Component {
constructor(props, context) {
super(props, context);

// what you would have put in componentWillMount
}

...
}

React 文档本身有更多详细信息,但基本上 React.createClass 购买的唯一附加功能是 mixins,但据我所知,您可以使用 mixins 完成的任何操作都可以使用上下文和更高阶的组件来完成。

关于reactjs - React.Component 与 React.createClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30668464/

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