脚本宝典收集整理的这篇文章主要介绍了React 最佳实践,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
整体结构
class List extends React.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
};
constructor(props) {
super(props);
this.state = {
foo: 'bar'
};
}
render() {
return <div>{this.state.foo}</div>;
}
}
基础规范
方法顺序
propTypes
defaultProps
constructor()
getChildContext()
componentWillmount()
componentDidMount()
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
componentDidUpdate()
componentWillUnmount()
render()
引号
JSX属性值使用双引号,其他均使用单引号;
<Foo bar="bar" />
<Foo style={{ left: '20px' }} />
空格
总是在自闭合的标签/>
前加一个空格;
不要在JSX{}
引用括号里两边加空格。
<Foo />
<Foo bar={baz} />
括号
将多行的JSX标签写在()
里;
render() {
return (<MyComponent classname="long body" foo="bar">
<MyChild />
</MyComponent>);
}
标签
对于没有子元素的标签来说总是闭合的;
<Foo className="stuff" />
组件定义
如果有内部状态、方法或是要对外暴露ref的组件,使用ES6 Class
写法;
class List extends React.Component {
// ...
render() {
return <div>{this.state.hello}</div>;
}
}
否则的话,使用函数写法;
const List = ({ hello }) => (
<div>{hello}</div>
);
PropsType 和 DefaultProps 写法
如果有内部状态、方法或是要对外暴露ref的组件,使用es7
类静态属性写法;
JSX属性名使用驼峰式风格。
如果属性值为true, 可以直接省略。
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
};
render() {
// ....
}
}
否则的话,使用类静态属性写法
const HelloMessage = ({ name }) => {
return <div>Hello {name}</div>;
};
HelloMessage.propTypes = {
name: React.PropTypes.string
};
HelloMessage.defaultProps = {
name: 'vic'
};
State 写法
使用ES7实例属性提案声明写法或者构造函数声明写法,后者适合需要进行一定计算后才能初始化state的情况。
class Some extends Component {
state = {
foo: 'bar'
};
// ....
}
class Some extends Component {
constructor(props) {
super(props);
this.state = {
foo: 'bar'
};
}
// ....
}
函数绑定
在使用ES6编写React时,不会将方法内部的作用域自动绑定到组件的引用上。
为此有以下几种写法仅供参考:
参考
以上是脚本宝典为你收集整理的React 最佳实践全部内容,希望文章能够帮你解决React 最佳实践所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。