Skip to content

React 代码规范

Posted on:April 2, 2020 at 04:51 PM

基本规范

文件规范

命名规范

带命名空间的组件

class Form extends React.Component {  
  // ...
}

class Row extends React.Component {}
class Label extends React.Component {}
class Input extends React.Component {}

Form.Row = Row;
Form.Label = Label;
Form.Input = Input;

export default Form;

// refence Form component
import Form from './Form';

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

属性

属性设置

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

属性对齐方式

// 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')}
 />

属性空格

// bad
<Foo bar={ baz } foo = "bar" />

// good
<Foo bar={baz} foo="bar" />

// good { left: '20px' } 为一个对象
<Foo style={{ left: '20px' }} />

propTypes 及默认值

// bad
function SFC({ foo, bar, children }) {
  return <div>{foo}{bar}{children}</div>;
}


// good
function SFC({ foo, bar, children }) {
  return <div>{foo}{bar}{children}</div>;
}

SFC.propTypes = {
  foo: PropTypes.number.isRequired,
  bar: PropTypes.string,
  children: PropTypes.node,
};

SFC.defaultProps = {
  bar: '',
  children: null,
};

引号

() 使用

// bad
 return (<div><ComponentOne /><ComponentTwo /></div>);

 // good
 var multilineJsx = (  
   <header>
     <Logo />
     <Nav />
   </header>
 );

 // good
 return (
   <div>
     <ComponentOne />
     <ComponentTwo />
   </div>
);

自闭合标签

// bad
<Logo></Logo>

// very bad
<Foo                 />

// bad
<Foo
 />

// good
<Logo />

方法

// good
class Foo extends React.Component {
  handleClick = () => {
    this.setState({ xxx: aaa })
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    )
  }
}

// bad
class Foo extends React.Component {
  handleClick () {
    this.setState({ xxx: aaa })
  }

  render() {
    return (
      <button onClick={this.handleClick.bind(this)}>
        Click me
      </button>
    )
  }
}

组件代码组织

代码校验工具

参考:https://github.com/minwe/style-guide/blob/master/React.js.md

参考:JasonBoy/javascript