Reactjs:与普通函数相比,使用 React 组件是否有优势?
Reactjs: Are there advantages to using React components over normal functions?
以 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'))
如果您不使用 JSX,并且不需要核心 类(如 componentDidMount
等)的任何 运行 时间特性,则没有不必要地创建 类 的优势,事实上,它总体上会(稍微)更有效率。
通过创建具体的(但非常简单的)包装函数,例如您在 Avatar
中所做的那样,它提高了代码的可读性。但是,如果您确实开始使用 JSX,则需要切换到 createClass
以便正确传递属性(因为初始属性不会像在代码中那样传递给构造函数)。
以 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'))
如果您不使用 JSX,并且不需要核心 类(如 componentDidMount
等)的任何 运行 时间特性,则没有不必要地创建 类 的优势,事实上,它总体上会(稍微)更有效率。
通过创建具体的(但非常简单的)包装函数,例如您在 Avatar
中所做的那样,它提高了代码的可读性。但是,如果您确实开始使用 JSX,则需要切换到 createClass
以便正确传递属性(因为初始属性不会像在代码中那样传递给构造函数)。