React课堂笔记第十讲(编码规范)
Airbnb React/JSX Style Guide
A mostly reasonable approach to React and JSX
目录
- Basic Rules
- Class vs
React.createClass
vs stateless - Naming
- Declaration
- Alignment
- Quotes
- Spacing
- Props
- Parentheses
- Tags
- Methods
- Ordering
isMounted
Basic Rules
- Only include one React component per file.
- However, multiple Stateless, or Pure, Components are allowed per file. eslint:
react/no-multi-comp
.
- However, multiple Stateless, or Pure, Components are allowed per file. eslint:
- Always use JSX syntax.
- Do not use
React.createElement
unless you’re initializing the app from a file that is not JSX.
Class vs React.createClass
vs stateless
If you have internal state and/or refs, prefer
class extends React.Component
overReact.createClass
unless you have a very good reason to use mixins. eslint:react/prefer-es6-class
react/prefer-stateless-function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// bad
const Listing = React.createClass({
// ...
render() {
return <div>{this.state.hello}</div>;
}
});
// good
class Listing extends React.Component {
// ...
render() {
return <div>{this.state.hello}</div>;
}
}And if you don’t have state or refs, prefer normal functions (not arrow functions) over classes:
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 (relying on function name inference is discouraged)
const Listing = ({ hello }) => (
<div>{hello}</div>
);
// good
function Listing({ hello }) {
return <div>{hello}</div>;
}
Naming
- Extensions: Use
.jsx
extension for React components. - Filename: Use PascalCase for filenames. E.g.,
ReservationCard.jsx
. Reference Naming: Use PascalCase for React components and camelCase for their instances. eslint:
react/jsx-pascal-case
1
2
3
4
5
6
7
8
9
10
11// bad
import reservationCard from './ReservationCard';
// good
import ReservationCard from './ReservationCard';
// bad
const ReservationItem = <ReservationCard />;
// good
const reservationItem = <ReservationCard />;Component Naming: Use the filename as the component name. For example,
ReservationCard.jsx
should have a reference name ofReservationCard
. However, for root components of a directory, useindex.jsx
as the filename and use the directory name as the component name:1
2
3
4
5
6
7
8// bad
import Footer from './Footer/Footer';
// bad
import Footer from './Footer/index';
// good
import Footer from './Footer';
Declaration
Do not use
displayName
for naming components. Instead, name the component by reference.1
2
3
4
5
6
7
8
9// bad
export default React.createClass({
displayName: 'ReservationCard',
// stuff goes here
});
// good
export default class ReservationCard extends React.Component {
}
Alignment
Follow these alignment styles for JSX syntax. eslint:
react/jsx-closing-bracket-location
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20// bad
<Foo superLongParam="bar"
anotherSuperLongParam="baz" />
// good
<Foo
superLongParam="bar"
anotherSuperLongParam="baz"
/>
// if props fit in one line then keep it on the same line
<Foo bar="bar" />
// children get indented normally
<Foo
superLongParam="bar"
anotherSuperLongParam="baz"
>
<Quux />
</Foo>
Quotes
Always use double quotes (
"
) for JSX attributes, but single quotes for all other JS. eslint:jsx-quotes
Why? JSX attributes can’t contain escaped quotes, so double quotes make conjunctions like
"don't"
easier to type.
Regular HTML attributes also typically use double quotes instead of single, so JSX attributes mirror this convention.1
2
3
4
5
6
7
8
9
10
11// bad
<Foo bar='bar' />
// good
<Foo bar="bar" />
// bad
<Foo style={{ left: "20px" }} />
// good
<Foo style={{ left: '20px' }} />
Spacing
Always include a single space in your self-closing tag.
1
2
3
4
5
6
7
8
9
10
11
12// bad
<Foo/>
// very bad
<Foo />
// bad
<Foo
/>
// good
<Foo />Do not pad JSX curly braces with spaces. eslint:
react/jsx-curly-spacing
1
2
3
4
5// bad
<Foo bar={ baz } />
// good
<Foo bar={baz} />
Props
Always use camelCase for prop names.
1
2
3
4
5
6
7
8
9
10
11// bad
<Foo
UserName="hello"
phone_number={12345678}
/>
// good
<Foo
userName="hello"
phoneNumber={12345678}
/>Omit the value of the prop when it is explicitly
true
. eslint:react/jsx-boolean-value
1
2
3
4
5
6
7
8
9// bad
<Foo
hidden={true}
/>
// good
<Foo
hidden
/>Always include an
alt
prop on<img>
tags. If the image is presentational,alt
can be an empty string or the<img>
must haverole="presentation"
. eslint:jsx-a11y/img-has-alt
1
2
3
4
5
6
7
8
9
10
11// bad
<img src="hello.jpg" />
// good
<img src="hello.jpg" alt="Me waving hello" />
// good
<img src="hello.jpg" alt="" />
// good
<img src="hello.jpg" role="presentation" />Do not use words like “image”, “photo”, or “picture” in
<img>
alt
props. eslint:jsx-a11y/img-redundant-alt
Why? Screenreaders already announce
img
elements as images, so there is no need to include this information in the alt text.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" />Use only valid, non-abstract ARIA roles. eslint:
jsx-a11y/aria-role
1
2
3
4
5
6
7
8// bad - not an ARIA role
<div role="datepicker" />
// bad - abstract ARIA role
<div role="range" />
// good
<div role="button" />Do not use
accessKey
on elements. eslint:jsx-a11y/no-access-key
Why? Inconsistencies between keyboard shortcuts and keyboard commands used by people using screenreaders and keyboards complicate accessibility.
1
2
3
4
5// bad
<div accessKey="h" />
// good
<div />
Parentheses
Wrap JSX tags in parentheses when they span more than one line. eslint:
react/wrap-multilines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21// bad
render() {
return <MyComponent className="long body" foo="bar">
<MyChild />
</MyComponent>;
}
// good
render() {
return (
<MyComponent className="long body" foo="bar">
<MyChild />
</MyComponent>
);
}
// good, when single line
render() {
const body = <div>hello</div>;
return <MyComponent>{body}</MyComponent>;
}
Tags
Always self-close tags that have no children. eslint:
react/self-closing-comp
1
2
3
4
5// bad
<Foo className="stuff"></Foo>
// good
<Foo className="stuff" />If your component has multi-line properties, close its tag on a new line. eslint:
react/jsx-closing-bracket-location
1
2
3
4
5
6
7
8
9
10// bad
<Foo
bar="bar"
baz="baz" />
// good
<Foo
bar="bar"
baz="baz"
/>
Methods
Use arrow functions to close over local variables.
1
2
3
4
5
6
7
8
9
10
11
12function ItemList(props) {
return (
<ul>
{props.items.map((item, index) => (
<Item
key={item.key}
onClick={() => doSomethingWith(item.name, index)}
/>
))}
</ul>
);
}Bind event handlers for the render method in the constructor. eslint:
react/jsx-no-bind
Why? A bind call in the render path creates a brand new function on every single render.
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} />
}
}Do not use underscore prefix for internal methods of a React component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17// bad
React.createClass({
_onClickSubmit() {
// do stuff
},
// other stuff
});
// good
class extends React.Component {
onClickSubmit() {
// do stuff
}
// other stuff
}Be sure to return a value in your
render
methods. eslint:require-render-return
1
2
3
4
5
6
7
8
9// bad
render() {
(<div />);
}
// good
render() {
return (<div />);
}
Ordering
- Ordering for
class extends React.Component
:
- optional
static
methods constructor
getChildContext
componentWillMount
componentDidMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentWillUnmount
- clickHandlers or eventHandlers like
onClickSubmit()
oronChangeDescription()
- getter methods for
render
likegetSelectReason()
orgetFooterContent()
- Optional render methods like
renderNavigation()
orrenderProfilePicture()
render
How to define
propTypes
,defaultProps
,contextTypes
, etc…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
26import React, { PropTypes } from 'react';
const propTypes = {
id: PropTypes.number.isRequired,
url: PropTypes.string.isRequired,
text: PropTypes.string,
};
const defaultProps = {
text: 'Hello World',
};
class Link extends React.Component {
static methodsAreOk() {
return true;
}
render() {
return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a>
}
}
Link.propTypes = propTypes;
Link.defaultProps = defaultProps;
export default Link;Ordering for
React.createClass
: eslint:react/sort-comp
displayName
propTypes
contextTypes
childContextTypes
mixins
statics
defaultProps
getDefaultProps
getInitialState
getChildContext
componentWillMount
componentDidMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentWillUnmount
- clickHandlers or eventHandlers like
onClickSubmit()
oronChangeDescription()
- getter methods for
render
likegetSelectReason()
orgetFooterContent()
- Optional render methods like
renderNavigation()
orrenderProfilePicture()
render
isMounted
Do not use
isMounted
. eslint:react/no-is-mounted
Why?
isMounted
is an anti-pattern, is not available when using ES6 classes, and is on its way to being officially deprecated.