代码写作规范-Airbnb

作者 Zwe1 日期 2018-04-13
代码写作规范-Airbnb

React编码规范

  • 组件中未使用refs或state时,更好的方式使用普通函数(非箭头函数)替代类。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// bad (考虑到创建一个类会产生一系列的副作用,而需求很简单)
class Listing extends React.Component {
render() {
return <div>{this.props.hello}</div>;
}
}

// bad
const Listing = ({ hello }) => (
<div>{hello}</div>
);

// good
function Listing({ hello }) {
return <div>{hello}</div>;
}
  • 命名
1
2
3
4
5
export default class ReservationCard;

import ReservationCard from './ReservationCard';

const reservationItem = <ReservationCard />;

组件名和组件的文件名采用相同的帕斯卡命名,即驼峰式命名首字母大写。
组件实例采用驼峰命名。

  • 代码对齐
1
2
3
4
5
6
7
8
9
// bad
<Foo superLongParam="bar"
anotherSuperLongParam="baz" />

// good, 有多行属性的话, 新建一行关闭标签
<Foo
superLongParam="bar"
anotherSuperLongParam="baz"
/>
  • 空格
1
2
3
4
5
6
7
8
// bad
<Foo
/>

// good
<Foo />

<Foo width={ 50 } />

在自动关闭的标签前加一个空格。

  • img标签要加alt属性
1
2
3
4
5
// bad
<img src="hello.jpg" alt="Picture of me waving hello" />

// good
<img src="hello.jpg" alt="Me waving hello" />
  • 括号
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bad
render() {
return <MyComponent className="long body" foo="bar">
<MyChild />
</MyComponent>;
}

// good
render() {
return (
<MyComponent className="long body" foo="bar">
<MyChild />
</MyComponent>
);
}

多行JSX标签写在()里,单行可直接书写。

  • 提前绑定this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// bad
class extends React.Component {
onClickDiv() {
// do stuff
}

render() {
return <div onClick={this.onClickDiv.bind(this)} />;
}
}

// good
class extends React.Component {
constructor(props) {
super(props);

this.onClickDiv = this.onClickDiv.bind(this);
}

onClickDiv() {
// do stuff
}

render() {
return <div onClick={this.onClickDiv} />;
}
}

在render过程中使用bind绑定this,每次都会新建一个新的函数,浪费资源。可提前绑定在构造函数里。