精益 React 学习指南 (Lean React)- 4.1 react 代码规范
4.1 react 代码规范
关于在代码的设计上,每个团队可能都有一定的代码规范和模式,好的代码规范能够提高代码的可读性便于协作沟通,好的模式能够上层设计上避免不必要的 bug 出现。本节会参考社区提供一些 React 的规范和优秀的设计模式。 基础规范
组件结构总体规则: stateless(Function) 优先于 Es6 Class 优先于 React.createClass;
以 Es6 Class 定义的组件为例; const defaultProps = { name: 'Guest' }; const propTypes = { name: React.PropTypes.string }; class Person extends React.Component { // 构造函数 constructor (props) { super(props); // 定义 state this.state = { smiling: false }; // 定义 eventHandler this.handleClick = this.handleClick.bind(this); } // 生命周期方法 componentWillMount () {},componentDidMount () {},componentWillUnmount () {},// getters and setters get attr() {} // handlers handleClick() {},// render renderChild() {},render () {},} /** * 类变量定义 */ Person.defaultProps = defaultProps; /** * 统一都要定义 propTypes * @type {Object} */ Person.propTypes = propTypes; 命名规范
jsx 书写规范
// bad <Foo className="stuff"></Foo> // good <Foo className="stuff" />
// bad <Foo superLongParam="bar" anotherSuperLongParam="baz" /> // good <Foo superLongParam="bar" anotherSuperLongParam="baz" /> // if props fit in one line then keep it on the same line <Foo bar="bar" />
// bad render() { return <MyComponent className="long body" foo="bar"> <MyChild /> </MyComponent>; } // good render() { return ( <MyComponent className="long body" foo="bar"> <MyChild /> </MyComponent> ); } // good,when single line render() { const body = <div>hello</div>; return <MyComponent>{body}</MyComponent>; } eslint-plugin-react规范可以使用 eslint-plugin-react 插件来强制实施,规则和配置可查看
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |