简体   繁体   English

在React.js中创建组件:“ React.createClass”是否仍然可用?

[英]Creating a component in React.js: is “React.createClass” still usable?

Some months ago I began to study react.js, then I abandoned it. 几个月前,我开始研究react.js,然后放弃了它。 Today I have begun to study React again. 今天,我开始重新学习React。 Reading the the official documentation I find that the syntax of how to create a component has changed. 阅读官方文档后,我发现如何创建组件的语法已更改。 In the past I learned to create a component in this way: 过去,我学会了以这种方式创建组件:

reactComponentElement = React.createClass({
   render: function(){
      return <h1>Title</h1>;
   }
})

so, using React.createClass. 因此,使用React.createClass。

Today I see in the docs that the creation of a component can be achieved with a function 今天,我在文档中看到可以使用功能来实现组件的创建

function reactComponentElement(){
   return <h1>Title</h1>;
}

or with a class 或同班

class Clock extends React.Component {
   render() {
      return (
         <div>
            <h1>Hello, world!</h1>
         </div>
      );
   }
}

So, can I still use React.createClass? 所以,我仍然可以使用React.createClass吗?

If I am coding in ES 5.1 I am still using the syntax: 如果我在ES 5.1中编码,我仍在使用以下语法:

var ComponentName = React.createClass({
    render: function() {
        return (
            <some JSX />
        )
    }
})

However, when I am writing ES 6 syntax, I use the extends declaration if I want a 'smart' or class based component (one that displays and messes with data): 但是,当我编写ES 6语法时,如果我想要一个“智能”或基于类的组件(可以显示并弄乱数据的组件),则可以使用extends声明:

import React, { Component } from 'react'

class ComponentName extends Component {
    render() {
        return (
            <some JSX />
        )
    }
}

But not every component needs that and I can just as well declare functional components (I call these 'dumb' components because I simply use those to get something on the screen) in ES 6: 但是并不是每个组件都需要它,因此我可以在ES 6中声明功能组件(我称它们为“哑”组件,因为我只是使用它们来在屏幕上显示内容):

const ComponentName = () => {
    return (
        <some JSX />
    )
}

I noticed in the React documentation that there is a mismatch between ES5 and ES 6 syntax (as in some pages are still in ES 5, others are in ES 6). 我在React文档中注意到ES5和ES 6语法之间不匹配(因为某些页面仍在ES 5中,其他页面在ES 6中)。 You can find the ES6 syntax here: https://facebook.github.io/react/docs/react-component.html 您可以在这里找到ES6语法: https ://facebook.github.io/react/docs/react-component.html

In function 在功能上

function reactComponentElement(){
   return <h1>Title</h1>;
}

you are not creating react component wit all it's meaning - you just return some JSX. 您并不是在创建具有所有含义的react组件-您只需返回一些JSX。 Classes are available only in ES6 and higher, so if you code in ES5, you still have to use React.createClass(); 类仅在ES6和更高版本中可用,因此,如果您在ES5中进行编码,则仍然必须使用React.createClass();。 React.Component React.Component

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM