前端代码规范

126 阅读1分钟

代码规范

React

圆括号

当 JSX 标签超过一行时使用圆括号包裹, eslint: react/wrap-multilines

// 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: react/jsx-closing-bracket-location

// bad
<Foo
  bar='bar'
  baz='baz' />
​
// good
<Foo
  bar='bar'
  baz='baz'
/>

遵循以下JSX语法的对齐风格,eslint: react/jsx-closing-bracket-location

// 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'
>
  <Quux />
</Foo>
​
// bad
{showButton &&
  <Button />
}
​
// bad
{
  showButton &&
    <Button />
}
​
// good
{showButton && (
  <Button />
)}
​
// good
{showButton && <Button />}