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' }} /> 空格
<Foo /> <Foo bar={baz} /> 括号 将多行的JSX标签写在 render() { return (<MyComponent className="long body" foo="bar"> <MyChild /> </MyComponent>); } 标签 对于没有子元素的标签来说总是闭合的; <Foo className="stuff" /> 组件定义 如果有内部状态、方法或是要对外暴露ref的组件,使用 class List extends React.Component { // ... render() { return <div>{this.state.hello}</div>; } } 否则的话,使用函数写法; const List = ({ hello }) => ( <div>{hello}</div> ); PropsType 和 DefaultProps 写法 如果有内部状态、方法或是要对外暴露ref的组件,使用 class Button extends Component { static propTypes = { size: React.PropTypes.oneOf(['large',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时,不会将方法内部的作用域自动绑定到组件的引用上。 参考
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |