【问题标题】:Difference between 2 ways of defining components in ReactJs [duplicate]ReactJs中定义组件的两种方式之间的区别[重复]
【发布时间】:2017-09-16 19:11:48
【问题描述】:

我遇到了两种在 ReactJs 中声明组件的方式。两者似乎都可以正常工作有什么不同!

案例一:

function Roger(props){
    return <h1>Hello! {props.name},{props.message}</h1>;
}

案例二:

var Roger = React.createClass({
  render: function() {
    return (
      <h1>Hello! {props.name},{props.message}</h1>
    );
  }
});

谁能帮助我理解差异?

【问题讨论】:

标签: javascript reactjs components


【解决方案1】:

案例 I 正在创建无状态功能组件,根据经验,建议尽可能使用它。例如,如果您需要使用 this 或者如果您需要生命周期方法,则案例 II 很有用。

查看这篇精彩的帖子以了解更多信息:http://jamesknelson.com/should-i-use-react-createclass-es6-classes-or-stateless-functional-components/

来自官方文档:

定义组件的最简单方法 就是写一个JavaScript函数:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

这个函数是一个有效的 React 组件,因为它接受单个 带有数据的“props”对象参数并返回一个 React 元素。我们称之为 这样的组件是“功能性的”,因为它们实际上是 JavaScript 功能。

您也可以使用 ES6 类来定义组件:

class Welcome extends React.Component {   
  render() {
    return <h1>Hello, {this.props.name}</h1>;   
  } 
}

从 React 的角度来看,上述两个组件是等价的。

类有一些额外的特性,我们将在接下来讨论 部分。在那之前,我们将使用功能组件 简洁。

来源:https://facebook.github.io/react/docs/components-and-props.html#functional-and-class-components

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    相关资源
    最近更新 更多