【问题标题】:Reactjs: Are there advantages to using React components over normal functions?Reactjs:使用 React 组件比普通函数有优势吗?
【发布时间】:2015-02-12 10:29:22
【问题描述】:

以 React.js 文档中的 this sample 为例

var Avatar = React.createClass({
  render: function() {
    return (
      <div>
        <ProfilePic username={this.props.username} />
        <ProfileLink username={this.props.username} />
      </div>
    );
  }
});

var ProfilePic = React.createClass({
  render: function() {
    return (
      <img src={'http://graph.facebook.com/' + this.props.username + '/picture'} />
    );
  }
});

var ProfileLink = React.createClass({
  render: function() {
    return (
      <a href={'http://www.facebook.com/' + this.props.username}>
        {this.props.username}
      </a>
    );
  }
});

React.render(
  <Avatar username="pwh" />,
  document.getElementById('example')
);

对于这样的情况,组件没有状态,如果我要使用 jsx:只使用函数而不是创建组件有什么缺点(性能或其他方面)吗? IE,把它简化成这样的东西(用 ES6 编写)

var { a, div, img } = React.DOM;

var Avatar = (username) =>
    div({}, ProfilePic(username), ProfileLink(username));

var ProfilePic = (username) => 
    img({src: `http://graph.facebook.com/${username}/picture`});

var ProfileLink = (username) =>
    a({href: `http://www.facebook.com/${username}`}, username);

React.render(Avatar(username), document.getElementById('example'))

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    如果你不使用 JSX,并且不需要核心类的任何运行时特性(如 componentDidMount 等),那么不必要地创建类是没有好处的,事实上,它总体上会(稍微)更有效率。

    通过创建具体的(但非常简单的)包装函数,例如您在Avatar 中所做的,它提高了代码的可读性。但是,如果您确实开始使用 JSX,则需要切换到 createClass 以便正确传递属性(因为初始属性不会像在您的代码中那样传递给构造函数)。

    【讨论】:

    • 非常感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 2021-07-29
    • 2014-04-17
    • 2017-11-28
    • 2021-11-10
    • 2014-04-09
    相关资源
    最近更新 更多