
1、每个文件只写一个组件,但是多个无状态组件可以放在单个文件中;
2、有内部状态,方法或要对外暴露ref的组件,用类式组件;
3、无内部状态,方法或无需对外暴露ref的组件,用函数式组件;
4、有内部状态,方法或要对外暴露ref的组件,使用es7类静态属性;
class Button extends Component { static propTypes = { size: React.PropTypes.oneOf(['large', 'normal', 'small']), shape: React.PropTypes.oneOf(['default', 'primary', 'ghost']), disabled: React.PropTypes.bool }; static defaultProps = { size: 'normal', shape: 'default', disabled: false }; }
5、无内部状态,方法或无需对外暴露ref的组件,使用类静态属性写法;
const HelloMessage = ({name}) => { return <div>Hello {name} </div>; } HelloMessage.propTypes = { name: React.PropTypes.string }; HelloMessage.defaultProps = { name: 'camille666' }
6、PropTypes必须;
7、为了调试方便,在组件最上方写displayName;
class Some extends Component { static displayName = 'Some'; }
8、react组件文件用jsx,用大驼峰命名jsx文件;
9、jsx的属性值总是使用双引号,其他用单引号;
<Foo bar="bar"/> <Foo style={{ left: '20px' }} />
10、在自闭合组件前加一个空格;
<Foo />
11、不要在jsx{}里两边加空格;
<Foo bar={baz} />
12、不要在等号两边加空格;
<Foo bar={baz} />
13、jsx属性名总是使用驼峰式风格;
14、如果属性值为true,可以直接省略;
<Foo hidden />
15、遍历数组,输出相同的React组件,属性key必须;
[<Hello key="first" />, <Hello key="second" />, <Hello key="third" />]
16、总是在Refs里使用回调函数;
<Foo ref={ref => { this.myRef = ref; }} />
17、将多行的jsx标签写在()里,单行可忽略();
// 在render方法中 return <div>dddd</div>;
return ( <MyCom className="box">我是一个盒子</MyCom> )
18、render方法必须有值返回;
19、没有子元素,自闭合;
<MyCom className="box" />
20、按照以下顺序排序方法;
A、static methods and properties B、lifecycle methods: displayName, propTypes, contextTypes , childContextTypes, mixins, statics, defaultProps, constructor, getDefaultProps, getInitialState, state, getChildContext, componentWillMount, componentDidMount, componentWillReceiveProps, shouldComonentUpdate, componentWillUpdate, componentDidUpdate, componentWillUnmount C、custom methods D、render method
21、不要在componentDidMount或componentDidUpdate中调用setState,除非在绑定回调函数中设置State;
class Hello extends Component { componentDidMount() { this.onMount(newName => { this.setState({ name: newName }); }); } render() { return <div>Hello {this.state.name}</div>; } }
22、不要给函数添加下划线前缀;
下划线前缀在某些语言中通常表示私有变量或者函数,但是js中没有原生支持所谓的私有变量,所有的变量函数都是共有的。