React/JSX 编码规范 #

基本规范 #

命名规范 #

带命名空间的组件 #

var Form = MyFormComponent;

var App = (
  <Form>
    <Form.Row>
      <Form.Label />
      <Form.Input />
    </Form.Row>
  </Form>
);
```

组件声明 #

属性 #

属性命名 #

传递给 HTML 的属性:

属性设置 #

var component = <Component />;
component.props.foo = x; // bad
component.props.bar = y; // also bad

// good
var component = <Component foo={x} bar={y} />;

// good
var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;

var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'

属性对齐方式 #

// bad - too long
<input type="text" value={this.state.newDinosaurName} onChange={this.inputHandler.bind(this, 'newDinosaurName')} />  

// bad - aligning attributes after the tag
<input type="text"  
       value={this.state.newDinosaurName}
       onChange={this.inputHandler.bind(this, 'newDinosaurName')} />

// good
<input  
  type="text"
  value={this.state.newDinosaurName}
  onChange={this.inputHandler.bind(this, 'newDinosaurName')}
 />

 // 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>


// bad
<Foo
  bar="bar"
  baz="baz" />

// good
<Foo
  bar="bar"
  baz="baz"
/>

行内迭代 #

return (
  <div>
    {this.props.data.map(function(data, i) {
      return (<Component data={data} key={i} />)
    })}
    </div>
);

其他代码格式 #

注释 #

引号使用 #

// bad
<Foo bar='bar' />

// good
<Foo bar="bar" />

// bad
<Foo style={{ left: "20px" }} />

// good
<Foo style={{ left: '20px' }} />

// JavaScript Expression
const person = <Person name={window.isLoggedIn ? window.name : ''} />;

// HTML/JSX
const myDivElement = <div className="foo" />;
const app = <Nav color="blue" />;
const content = (
  <Container>
    {window.isLoggedIn ? <Nav /> : <Login />}
  </Container>
);

条件 HTML #

() 使用 #

自闭合标签 #

// bad
<Logo></Logo>
<Logo/>

// very bad
<Foo                 />

// bad
<Foo
 />

// good
<Logo />

组件内部代码组织 #

```js
// React 组件中按照以下顺序组织代码
React.createClass({  
  displayName: '',

  mixins: [],

  statics: {},

  propTypes: {},

  getDefaultProps() {
    // ...
  },

  getInitialState() {
    // do something
  },

  componentWillMount() {
      // do something
  },

  componentDidMount() {
    // do something: add DOM event listener, etc.
  },

  componentWillReceiveProps() {
  },

  shouldComponentUpdate() {},

  componentWillUpdate() {},

  componentDidUpdate() {},

  componentWillUnmount() {
      // do something: remove DOM event listener. etc.
  },

  // clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
  handleClick() {
    // ...
  },

  // getter methods for render like getSelectReason() or getFooterContent()

  // Optional render methods like renderNavigation() or renderProfilePicture()

  render() {
    // ...
  }
});
```

代码校验工具 #

参考资源 #