React 編程規范

jopen 8年前發布 | 24K 次閱讀 React 移動開發

基本規則

  • 每個文件只包含一個 React 組件
  • 使用JSX語法
  • 除非是從一個非JSX文件中初始化 app,否則不要使用React.createElement
  • </ul>

    Class vs React.createClass

    • 除非有更好的理由使用混淆(mixins),否則就使用組件類繼承React.Component。eslint 規則:react/prefer-es6-class
    • </ul>

      // bad
      const Listing = React.createClass({
        render() {
          return <div />;
        }
      });

      // good class Listing extends React.Component { render() { return <div />; } }</pre>

      命名

      • 擴展名: 使用jsx作為 React 組件的擴展名
      • 文件名: 文件命名采用帕斯卡命名法,如:ReservationCard.jsx
      • 引用名: 組件引用采用帕斯卡命名法,其實例采用駝峰式命名法。eslint rules: react/jsx-pascal-case
      • </ul>

        // bad
        const reservationCard = require('./ReservationCard');

        // good const ReservationCard = require('./ReservationCard');

        // bad const ReservationItem = <ReservationCard />;

        // good const reservationItem = <ReservationCard />;</pre>

        • 組件命名: 使用文件名作為組件名。例如:ReservationCard.jsx組件的引用名應該是ReservationCard。然而,對于一個目錄的根組件,應該使用index.jsx作為文件名,使用目錄名作為組件名。
        • </ul>

          // bad
          const Footer = require('./Footer/Footer.jsx')

          // bad const Footer = require('./Footer/index.jsx')

          // good const Footer = require('./Footer')</pre>

          聲明

          • 不要通過displayName來命名組件,通過引用來命名組件
          • </ul>

            // bad
            export default React.createClass({
              displayName: 'ReservationCard',
              // stuff goes here
            });

            // good export default class ReservationCard extends React.Component { }</pre>

            對齊

            • 對于JSX語法,遵循下面的對齊風格。eslint rules: react/jsx-closing-bracket-location
            • </ul>

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

              引號

              • 對于JSX使用雙引號,對其它所有 JS 屬性使用單引號
              • </ul>

                為什么?因為 JSX 屬性不能包含被轉移的引號,并且雙引號使得如"don't"一樣的連接詞很容易被輸入。常規的 HTML 屬性也應該使用雙引號而不是單引號,JSX 屬性反映了這個約定。

                </blockquote>

                eslint rules: jsx-quotes

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

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

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

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

                空格

                • 在自閉和標簽之前留一個空格
                • </ul>

                  // bad
                  <Foo/>

                  // very bad <Foo />

                  // bad <Foo />

                  // good <Foo /></pre>

                  屬性

                  • 屬性名采用駝峰式命名法
                  • </ul>

                    // bad
                    <Foo
                      UserName="hello"
                      phone_number={12345678}
                    />

                    // good <Foo userName="hello" phoneNumber={12345678} /></pre>

                    括號

                    • 當組件跨行時,要用括號包裹 JSX 標簽。eslint rules: react/wrap-multilines
                    • </ul>

                      /// 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>; }</pre>

                      標簽

                      • 沒有子組件的父組件使用自閉和標簽。eslint rules: react/self-closing-comp
                      • </ul>

                        // bad
                          <Foo className="stuff"></Foo>

                        // good <Foo className="stuff" /></pre>

                        • 如果組件有多行屬性,閉合標簽應寫在新的一行上。eslint rules: react/jsx-closing-bracket-location
                        • </ul>

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

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

                          方法

                          • 不要對 React 組件的內置方法使用underscore前綴
                          • </ul>

                            // bad
                            React.createClass({
                              _onClickSubmit() {
                                // do stuff
                              }

                            // other stuff });

                            // good class extends React.Component { onClickSubmit() { // do stuff }

                            // other stuff });</pre>

                            順序

                            • 繼承 React.Component 的類的方法遵循下面的順序

                              </li> </ul>

                              1. constructor
                              2. optional static methods
                              3. getChildContext
                              4. componentWillMount
                              5. componentDidMount
                              6. componentWillReceiveProps
                              7. shouldComponentUpdate
                              8. componentWillUpdate
                              9. componentDidUpdate
                              10. componentWillUnmount
                              11. clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
                              12. getter methods for render like getSelectReason() or getFooterContent()
                              13. Optional render methods like renderNavigation() or renderProfilePicture()
                              14. render

                                </li> </ol>

                                • 怎么定義 propTypes,defaultProps,contextTypes 等等...
                                • </ul>

                                  import React, { PropTypes } from 'react';

                                  const propTypes = { id: PropTypes.number.isRequired, url: PropTypes.string.isRequired, text: PropTypes.string, };

                                  const defaultProps = { text: 'Hello World', };

                                  class Link extends React.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;

                                  export default Link;</pre>

                                  • 使用 React.createClass 時,方法順序如下:

                                    </li> </ul>

                                    1. displayName
                                    2. propTypes
                                    3. contextTypes
                                    4. childContextTypes
                                    5. mixins
                                    6. statics
                                    7. defaultProps
                                    8. getDefaultProps
                                    9. getInitialState
                                    10. getChildContext
                                    11. componentWillMount
                                    12. componentDidMount
                                    13. componentWillReceiveProps
                                    14. shouldComponentUpdate
                                    15. componentWillUpdate
                                    16. componentDidUpdate
                                    17. componentWillUnmount
                                    18. clickHandlers or eventHandlers like onClickSubmit() or onChangeDescription()
                                    19. getter methods for render like getSelectReason() or getFooterContent()
                                    20. Optional render methods like renderNavigation() or renderProfilePicture()
                                    21. render
                                    22. </ol>

                                      eslint rules: react/sort-comp

                                      來自:https://github.com/dwqs/react-style-guide

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!