var content = (
<Nav>
{/* child comment, put {} around */}
<Person
/* multi
line
comment */
name={window.isLoggedIn ? window.name : ''} // end of line comment
/>
</Nav>
);
// bad
return (<div><ComponentOne /><ComponentTwo /></div>);
// good
var multilineJsx = (
<header><Logo /><Nav /></header>
);
// good
return (
<div><ComponentOne /><ComponentTwo /></div>
);
单行 JSX 省略 ()。
var singleLineJsx = <h1>Simple JSX</h1>;
// good, when single line
render() {
const body = <div>hello</div>;
return <MyComponent>{body}</MyComponent>;
}
8.自闭合标签
JSX 中所有标签必须闭合;
没有子元素的组件使用自闭合语法,自闭合标签 / 前留一个空格。
// bad
<Logo></Logo><Logo/>
// very bad
<Foo />
// bad
<Foo
/>
// good
<Logo />
9.组件内部代码组织
不要使用下划线前缀命名 React 组件的方法;
// bad
React.createClass({
_onClickSubmit() {
// do stuff
}
// other stuff
});
// good
React.createClass({
onClickSubmit() {
// do stuff
}
// other stuff
});
按照生命周期组顺序织组件的方法、属性;
方法(属性)之间空一行;
.render() 方法始终放在最后;
自定义方法 React API 方法之后、.render() 之前。
// React 组件中按照以下顺序组织代码
React.createClass({
displayName: '',
mixins: [],
statics: {},
propTypes: {},
getDefaultProps() {
// ...
},
getInitialState() {
// do something
},
componentWillMount() {
// do something
},
componentDidMount() {
// do something: add DOM event listener, etc.
},
componentWillReceiveProps() {
},
shouldComponentUpdate() {},
componentWillUpdate() {},
componentDidUpdate() {},
componentWillUnmount() {
// do something: remove DOM event listener. etc.
},
// clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
handleClick() {
// ...
},
// getter methods for render like getSelectReason() or getFooterContent()
// Optional render methods like renderNavigation() or renderProfilePicture()
render() {
// ...
}
});