前端之React实战-代码规范
Coding Style(编码风格)Basic Rules(基本原则)
Component(组件规范)Class 与 React.createClass方法尽可能地使用ES6中的类的语法,除非有特殊的对于Mixin的需求。 // bad const Listing = React.createClass({ render() { return <div />; } }); // good class Listing extends React.Component { render() { return <div />; } } 组件命名
// bad const reservationCard = require('./ReservationCard'); // good const ReservationCard = require('./ReservationCard'); // bad const ReservationItem = <ReservationCard />; // good const reservationItem = <ReservationCard />; Declaration(声明)
// bad export default React.createClass({ displayName: 'ReservationCard',// stuff goes here }); // good export default class ReservationCard extends React.Component { } Props
// bad <Foo UserName="hello" phone_number={12345678} /> // good <Foo userName="hello" phoneNumber={12345678} />
import React,{ Component,PropTypes } from 'react'; const propTypes = { id: PropTypes.number.isRequired,url: PropTypes.string.isRequired,text: PropTypes.string,}; const defaultProps = { text: 'Hello World',}; export default class Link extends Component { static methodsAreOk() { return true; } render() { return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a> } } Link.propTypes = propTypes; Link.defaultProps = defaultProps; JSX(JSX规范)Alignment(对齐)
// 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" /> // children get indented normally <Foo superLongParam="bar" anotherSuperLongParam="baz" > <Spazz /> </Foo> Quotes对于JSX的属性用双引号表示,对于其他属性,用单引号表示。 // bad <Foo bar='bar' /> // good <Foo bar="bar" /> // bad <Foo style={{ left: "20px" }} /> // good <Foo style={{ left: '20px' }} /> Spacing(空格)
// bad <Foo/> // very bad <Foo /> // bad <Foo /> // good <Foo /> 多段
/// 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>; } MethodsNaming(方法命名)
// bad React.createClass({ _onClickSubmit() { // do stuff } // other stuff }); // good class extends React.Component { onClickSubmit() { // do stuff } // other stuff }); Ordering(顺序)
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |