React.createElement
创建 ReactElement,以提高编写速度、可读性、可维护性(没有 JSX 转换的特殊场景例外,如在 console
中测试组件)。.js
作为 React 组件的扩展名;MyComponent.js
;组件命名:组件名称和文件名一致,如 MyComponent.js
里的组件名应该是 MyComponent
;一个目录的根组件使用 index.js
命名,以目录名称作为组件名称;
// Use the filename as the component name
// file contents
const CheckBox = React.createClass({
// ...
})
module.exports = CheckBox;
// in some other file
// bad
const CheckBox = require('./checkBox');
// bad
const CheckBox = require('./check_box');
// good
const CheckBox = require('./CheckBox');
// for root components of a directory,
// use index.js as the filename and use the directory name as the component name
// bad
const Footer = require('./Footer/Footer.js')
// bad
const Footer = require('./Footer/index.js')
// good
const Footer = require('./Footer')
引用命名:React 组件使用大驼峰命名法,HTML 标签、组件实例使用小驼峰命名法;
// bad
const reservationCard = require('./ReservationCard');
// good
const ReservationCard = require('./ReservationCard');
// bad
const ReservationItem = <ReservationCard />;
// good
const reservationItem = <ReservationCard />;
// HTML tag
const myDivElement = <div className="foo" />;
React.render(myDivElement, mountNode);
如果一个组件有许多关联子组件,可以以该组件作为命名空间编写、调用子组件。
```js var MyFormComponent = React.createClass({ ... });
MyFormComponent.Row = React.createClass({ ... }); MyFormComponent.Label = React.createClass({ ... }); MyFormComponent.Input = React.createClass({ ... });
var Form = MyFormComponent;
var App = (
<Form>
<Form.Row>
<Form.Label />
<Form.Input />
</Form.Row>
</Form>
);
```
不要使用 displayName
来命名组件,通过引用来命名。
// bad
export default React.createClass({
displayName: 'ReservationCard',
// stuff goes here
});
// good
const ReservationCard = React.createClass({
// stuff goes here
});
export default ReservationCard;
className
代替 class
属性;htmlFor
代替 for
属性。传递给 HTML 的属性:
data-
前缀,React 不会渲染非标准属性;aria-
可以正常使用。propTypes
校验),不要在外部改变属性的值;{...this.props}
语法;var component = <Component />;
component.props.foo = x; // bad
component.props.bar = y; // also bad
// good
var component = <Component foo={x} bar={y} />;
// good
var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;
var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'
// bad - too long
<input type="text" value={this.state.newDinosaurName} onChange={this.inputHandler.bind(this, 'newDinosaurName')} />
// bad - aligning attributes after the tag
<input type="text"
value={this.state.newDinosaurName}
onChange={this.inputHandler.bind(this, 'newDinosaurName')} />
// good
<input
type="text"
value={this.state.newDinosaurName}
onChange={this.inputHandler.bind(this, 'newDinosaurName')}
/>
// 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"
>
<Spazz />
</Foo>
// bad
<Foo
bar="bar"
baz="baz" />
// good
<Foo
bar="bar"
baz="baz"
/>
return (
<div>
{this.props.data.map(function(data, i) {
return (<Component data={data} key={i} />)
})}
</div>
);
组件之间的注释需要用 {}
包裹。
var content = (
<Nav>
{/* child comment, put {} around */}
<Person
/* multi
line
comment */
name={window.isLoggedIn ? window.name : ''} // end of line comment
/>
</Nav>
);
"
;'
;// bad
<Foo bar='bar' />
// good
<Foo bar="bar" />
// bad
<Foo style={{ left: "20px" }} />
// good
<Foo style={{ left: '20px' }} />
// JavaScript Expression
const person = <Person name={window.isLoggedIn ? window.name : ''} />;
// HTML/JSX
const myDivElement = <div className="foo" />;
const app = <Nav color="blue" />;
const content = (
<Container>
{window.isLoggedIn ? <Nav /> : <Login />}
</Container>
);
简短的输出在行内直接三元运算符;
{this.state.show && 'This is Shown'}
{this.state.on ? 'On' : 'Off'}
较复杂的结构可以在 .render()
方法内定义一个以 Html
结尾的变量。
var dinosaurHtml = '';
if (this.state.showDinosaurs) {
dinosaurHtml = (
<section>
<DinosaurTable />
<DinosaurPager />
</section>
);
}
return (
<div>
...
{dinosaurHtml}
...
</div>
);
多行的 JSX 使用 ()
包裹,有组件嵌套时使用多行模式;
// 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>;
}
/
前留一个空格。// bad
<Logo></Logo>
<Logo/>
// very bad
<Foo />
// bad
<Foo
/>
// good
<Logo />
不要使用下划线前缀命名 React 组件的方法;
// bad
React.createClass({
_onClickSubmit() {
// do stuff
}
// other stuff
});
// good
React.createClass({
onClickSubmit() {
// do stuff
}
// other stuff
});
.render()
方法始终放在最后;.render()
之前。```js
// 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() {
// ...
}
});
```
px
的 style 属性