React 基礎知識分享

React 入門基礎

快速開始

由於 React 開發涉及 JSX 語法和ES6/7新語法還有開發環境和正式環境打包等等工做。建議新手可使用 Facebook 官方推出的 create-react-app快速開始學習基礎知識和代碼實踐。等到實際項目開發時能夠再深刻的進行 webpack 定製化開發。html

//全局安裝
  npm install -g create-react-app

  //建立項目
  create-react-app my-app
  cd my-app

  //運行
  npm start

  //測試
  npm test

  //打包
  npm run build

侷限性(不支持功能)

  • Server rendering. 服務器端渲染node

  • Some experimental syntax extensions (e.g. decorators).一些實驗性的語法(例如:修飾器)react

  • CSS Modules.webpack

  • LESS or Sass.git

  • Hot reloading of components.熱更新 本人本身開發的支持 redux hot reloading 項目react-startedes6

實際使用項目簡介 official-tutorial

改項目就是使用create-react-app建立的一個項目。主要實現了官方文檔 實際代碼react-tutorial代碼使用 ES5 Classes 方式來進行實現,能夠進行一個比較。其中省略了服務器端數據請求的邏輯。github

三種組件類型

React.createClass

import React, { Component } from 'react'

var TickTock = React.createClass({
  //類屬性和方法的設置
  statics: {
    customMethod: function(foo) {
      return foo === 'bar';
    }
    value: 0
  },
  //初始化 state 值
  getInitialState: function() {
    return {seconds: 0};
  },
  //定義 props 參數類型
  propTypes: {
    name: React.PropTypes.string
  },
  //設置 props 默認值
  getDefaultProps: function() {
    return {
      name: 'Mary'
    };
  },
  componentDidMount: function() {
    this.setInterval(this.tick, 1000); // Call a method on the mixin
  },
  tick: function() {
    this.setState({seconds: this.state.seconds + 1});
  },
  render: function() {
    return (
      <p>
        React has been running for {this.state.seconds} seconds.
      </p>
    );
  }
});

ES6 Classes export class Name extends React.Component

import React, { Component, PropTypes } from 'react'

export default class App extends Component{
  //靜態方法
  static customMethod(foo){
    return foo === 'bar';
  }
  constructor(){
    super()
    //初始化 state 值
    this.state = {
      data: []
    }
  }
  
  handleCommentSubmit(comment) {
    this.setState({
      data: [...this.state.data, comment]
    })
  }

  componentDidMount() {
    setTimeout(()=>{
      this.setState({
        data: data
      })
    }, 3000)
  }

  render() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList data={this.state.data} />
        <CommentForm onCommentSubmit={this.handleCommentSubmit.bind(this)} />
      </div>
    );
  }
}
//定義 props 參數類型
App.propTypes = {
  name: PropTypes.string
};
//設置 props 默認值
App.defaultProps = {
  name: 'Mary'
};
//類屬性
App.value = 1

純函數(pure funciton) stateless-functions

適用於無 state 的組件web

function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}
或者 ES6 箭頭函數
const Greeting = (props) => (
  <h1>Hello, {props.name}</h1>
);

ReactDOM.render(
  <Greeting name="Sebastian" />,
  document.getElementById('example')
);

參考連接:shell

component-specsnpm

reusable-components

選擇組件類型

阮一峯 ES6 教程 class

本身總結的小知識點

className 和 style

render(){
    return (
      <div className="demo-class" style={{
        height: "100px",
        width: "100px",
        fontSize: "12px"
      }}>
      </div>
    )
  }
  render(){
    const styleObj = {
      height: "100px",
      width: "100px",
      fontSize: "12px"
    }
    return (
      <div className="demo-class" style={styleObj}>
      </div>
    )
  }

JXS 註釋

render(){
    return (
      <div>
        {/* 這裏面的內容都是註釋 */}
      </div>
    )
  }

DOM 操做

ReactDOM.findDOMNode

export default class image extends Component {
      constructor(props) {
        super(props)
      }
      componentDidMount(){
        //獲取組件根 html DOM 元素對象
        let dom = findDOMNode(this)
      }
      render() {
        retrun <img/>
      }
  }

Refs to Comments

export default class Demo extends Component {
      constructor(props) {
        super(props)
      }
      componentDidMount(){
        //這是該組件的根 DOM 對象
        console.info(this.refs.comRootDom);
        this._input.focus();
      }
      render() {
        retrun (
          <div ref="comRootDom">
            {/* ref 還支持函數形式,函數輸入參數爲 DOM 對象 */}
            <TextInput ref={(input) => this._input = input} />
          </div>
        )
      }
  }

修改組件 state

要想修改 this.state 必須經過 this.setState 函數進行設置

constructor(){
    super()
    this.state = {
      data: [],
      counter: 0,
      other: 1
    }
  }
  onClick(){
    //如下代碼只會改版 this.state.counter 而不會影響 this.state.other 和 this.state.data
    this.setState({counter: this.state.counter + 1;
  }
  render(){
    <div className="commentBox">
      <h1>Comments</h1>
      <span>other {this.state.other}</span>
      <span onClick={
        //bind 是 bind 函數在 ECMA-262 第五版才被加入(即ES5) 語法中函數的新方法用於綁定函數做用域的
        this.onClick.bind(this)
      }>counter = {this.state.counter}</span>
      <CommentList data={this.state.data} />
      <CommentForm onCommentSubmit={this.handleCommentSubmit.bind(this)} />
    </div>
  }

MDN 對於 bind 的介紹

JSX 語法不支持 IF-ELSE 使用三元運算符或者使用變量獨立處理

JSX 中使用三元運算符

render(){
    return (
      <div>
        {
          this.state.isShow ? <span>show Text</span> : ""
        }
      </div>
    )
  }

使用變量獨立處理

render(){
    let content = "";
    if(this.state.isShow){
      content = <span>show Text</span>
    }
    return (
      <div>
        {content}
      </div>
    )
  }

生命週期

對於生命週期的理解很重要,生命週期貫徹 react 組件的整個使用過程


網絡圖片未找到出處,若有侵權請聯繫我刪除該圖片

Mounting: componentWillMount

能夠在這個函數中發情數據請求,此時進行 setState() render() 將只執行一次

Mounting: componentDidMount

第一次 render() 執行後,此時能夠讀取對真實DOM進行相關操做

Updating: componentWillReceiveProps(nextProps)

當組件 props 修改(即父組件傳遞參數變化),在第一次 render() 過程當中不執行此函數

變量 說明
this.props 老的 props
nextProps 新的 props

Updating: shouldComponentUpdate(nextProps, nextState)

若是配置該函數的話必須明確的返回 true 或者 false ,返回決定了本次變化是否引發組件重繪(及執行 render())。
在此函數中能夠進行邏輯性的判斷來減小組件重繪的次數

Updating: componentWillUpdate(nextProps, nextState)

請不要在此函數中執行修改 state 的邏輯(即調用 setState 函數),若有須要請在 componentWillReceiveProps 中進行修改設置

Updating: componentDidUpdate(prevProps, prevState)

完成組件更新(即完成本次更新重繪 render() 執行以後),此時能夠進行 DOM 操做

Unmounting: componentWillUnmount

組件被銷燬時調用,已經進行各類銷燬邏輯

render()

必須返回惟一包裹組件

render(){
    retrun (
      <div>
      </div>
    )
  }
  // good
  render(){
    retrun (
      <div>
      </div>
      {/* */}
    )
  }
  // error
  render(){
    retrun (
      <div>
      </div>
      <div>
      </div>
    )
  }
  // error

參考連接:

component-specs

相關文章
相關標籤/搜索