- 每个文件中只包含一个React组件。
- Class 与 React.createClass方法对比:尽可能地使用ES6中的类的语法,除非有特殊的对于Mixin的需求。
// bad
const Listing = React.createClass({
render() {
return <div />;
}
});
// good
class Listing extends React.Component {
render() {
return <div />;
}
}
- 关于命名
文件名:使用帕斯卡命名法命名文件,譬如ReservationCard.jsx。
引用命名:使用帕斯卡命名法命名组件和camelCase命名实例。
// bad
const reservationCard = require('./ReservationCard');
// good
const ReservationCard = require('./ReservationCard');
// bad
const ReservationItem = <ReservationCard />;
// good
const reservationItem = <ReservationCard />;
- 对于Props的命名使用camelCase
// bad
<Foo
UserName="hello"
phone_number={12345678}
/>
// good
<Foo
userName="hello"
phoneNumber={12345678}
/>
- 关于组件名与prop 的对其规范
// bad
<Foo superLongParam="bar"
anotherSuperLongParam="baz" />
// good
<Foo
superLongParam="bar"
anotherSuperLongParam="baz"
/>
// 一行可以写下的时候放在一行
<Foo bar="bar" />
// 否则按规范换行
<Foo
superLongParam="bar"
anotherSuperLongParam="baz"
>
<Spazz />
</Foo>
- 关于标签闭合
在自闭合的标签中仅使用单空格。
// bad
<Foo/>
// very bad
<Foo />
// bad
<Foo
/>
// good
<Foo />
- jsx代码
/// bad
render() {
return <MyComponent className="long body" foo="bar">
<MyChild />
</MyComponent>;
}
// good
render() {
return (
<MyComponent className="long body" foo="bar">
<MyChild />
</MyComponent>
);
}
// good 如果一行可以放下,可以写成单行的形式
render() {
const body = <div>hello</div>;
return <MyComponent>{body}</MyComponent>;
}
- 组件函数顺序
- constructor
- 静态方法
- componentWillMount
- componentDidMount
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- componentDidUpdate
- componentWillUnmount
- clickHandlers/eventHandlers 如:onClickSubmit() 、onChangeDescription()
- render中调用的获取数据的函数,如:getSelectReason() 、getFooterContent()
- render中调用的用于渲染的函数,如:renderNavigation()、renderProfilePicture()
- render