平時寫react 小技巧,不錯喲~

CalDuFaur 7年前發布 | 26K 次閱讀 React

  • Stateless function 無狀態組件

    平時寫組件用到比較多的就是無狀態組件,不但優雅,也是優化react性能的一種手段。
    const Greeting = ({ name, style }) => {
        return <div style={style}>{name}</div>
      };
  • Array as children 把數組數據渲染出來

    經常會遇到處理數組數據的情況,可以用下面的方式簡單的渲染出來。

    render() {
          return (
              (<ul>
                  {List.map((item) => (
                       <li>{item}</li>
                  ))}
              </ul>)
          )     
      }
  • 封裝基礎類組件

    比如 <input type="text" > 每次寫很麻煩吧,可以封裝一個成一個組件

    const input = (props) => {
          return <input type = {props.type} {...props} />
      }
  • Layout Component 布局組件

    組件可以分成很多類類,有的是布局類,有的是功能類。下面是一種布局類的組件。

    <FlexContainer>
        <div style={{ flex: 1 }}>{this.props.leftSide}</div>
        <div style={{ flex: 2 }}>{this.props.rightSide}</div>
      </FlexContainer>
  • Higher Order Component 高階組件

    高階組件很像decorator,提升組件的能力。比如你想一些組件里面使用一下功能,react-router 中

    import { withRouter } from 'react-router'
      withRouter(SomeComponent)

    例子:

    var Enhance = ComposedComponent => class extends React.Component {
        componentDidMount() {
          this.setState({ name: "李狗子" });
        }
        render() {
          return <ComposedComponent {...this.props} name = {this.state.name} />;
        }
      };
  • 受控組件,不受控組件

    項目中經常會用到這兩種情況如:

    受控組件,更新的時候需要使用this.setState

    constructor() {
          super();
          this.state = {value: ""}
      }
      render() {
          return <input type="text" value={this.state.value} />
      }

    不受控組件,主要需要通過ref來獲取input的值。

    render() {
          return <input type="text" ref="myInput" />
      }

    兩種方法都可以在特定的場合去使用,個人覺得數據相對重要的頁面需要使用受控組件會比較合適。

  • 使用三元表達式

    項目中經常有判斷語句,用三元表達式可以很方便的寫出想要的邏輯

    const demo = ({ isOK }) => {
          return isOK 
          ? <p> Yes </p> 
          : <p> No </p>
      };
  • 給setState傳入function

    可以使用function來更新state

    this.setState((prevState, props) => ({
          return ...
      }));
  • 通過ref屬性獲取component

    場景:下面的例子是初始化組件后,讓input默認獲取光標。ref最終指向的已經渲染好的DOM節點,或者是react class的實例。具體可以看官方的文檔

    componentDidMount() {
          this.input.focus();
      }
      render() {
          return (
              <input
                ref={comp => { this.input = comp; }}
              />
          )
      }
  • 切勿使用...props傳遞數據

    一個非常錯誤的做法比如:

    <Component {...props} />

    props上面如果有非常多的屬性,會造成非常昂貴的計算。正確的應該

    <Component name = { props.name } />

以上是平時寫React用到的一些寫法小技巧,說有用還蠻有用的!

 

參考:

https://github.com/vasanthk/react-bits

react 代碼規范

https://github.com/airbnb/javascript/tree/master/react

 

來自:https://juejin.im/post/58e641d60ce46300584c23fd

 

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