Web Framework
  • Introduction
  • Chapter1: Build Front-End Develope environment
    • 1.1.Install Sublime Text3 and packages
    • 1.2.Sublime plugin
      • 1.2.1.Package install control
      • 1.2.2.Emmet
      • 1.2.3.HTML-CSS-JS Prettify
      • 1.2.4 .SublimeLinter
      • 1.2.5.Install Sublime text Build system
      • 1.2.6.Pretty JSON
      • 1.2.7.SublimeHighlight
      • 1.2.8.SublimeAStyleFormatter
  • Chapter2: Angular.js
  • Chapter3: 3rd Party API
    • 3.function
  • Chapter4: React.js
    • 4.1.Introduction
    • 4.2.Getting started
    • 4.3.JSX
    • 4.4.life cycle
    • 4.5.Data flow: prop vs. prop.children, state
    • 4.6. Layout, Event Handing
    • 4.7.Using JQuery in React
    • 4.8.Using D3.js in React
    • 4.9.Dynamic Routing
  • Chapter5: Webpack
  • Chapter6: web driver IO & mocha
  • Chapter7: RWD
    • 7.1.利用Sass & media query在不使用框架下完成RWD
  • Chapter8: React native
Powered by GitBook
On this page
  • This section contain the following items:
  • 1.Introduction
  • 2.Getting started
  • 3.JSX
  • 4.life cycle
  • 5.Data flow: prop vs. prop.children, state
  • 6. Layout, Event Handing
  • 7.Using JQuery in React
  • 8.Using D3.js in React
  • 9.Dynamic Routing

Was this helpful?

Chapter4: React.js

This section contain the following items:

  • 1.Introduction

  • 2.Getting started

  • 3.JSX

  • 4.life cycle

  • 5.Data flow: prop vs. prop.children, state

  • 6.Layout, Event Handing

  • 7.Using JQuery in React

  • 8.Using D3.js in React

  • 9.Dynamic Routing

1.Introduction

React發源自Facebook的PHP框架XHP的一隻分支. XHP作為一個PHP框架, 旨在每次有請求進來時渲染整個畫面. React的產生就是為了把這種重新渲染畫面的PHP式工作流帶到客戶端應用中.

React本質上是一個狀態機, 他只關心兩件事:

1.更新DOM
 2.響應事件

React贏就贏在最小化了重繪, 並避免了不必要的DOM操作,這兩點都是公認的性能瓶頸

[reference]: React 引領未來的用戶介面開發框架

2.Getting started

1) Visit React.js website: https://facebook.github.io/react/docs/tutorial.html
  2) Download example
  3) just type "node server.js" and open broswer: localhotst:3000

3.JSX

3.1 what is JSX ?

3.2 複合組件

1.自定義組件
2.使用動態值
3.子節點

3.3 JSX跟HTML的差異

1.屬性
2.條件判斷
3.非DOM屬性
4.事件
5.註釋
6.特殊屬性
7.樣式

4.life cycle

可分為實例化, 存在期, 銷毀&清理期:

  • Initialization (實例化):

一個實例初次被創建時所調用的生命週期方法, 與其他各個後續實例被創建時所調用的方法略有不同.

  • getDefaultProps():

    • 只有第一次創建時會被調用, 在創建任意组件时,我们可以通过getDefaultProps方法给他定義一些属性.

    • 当我们需要在render方法使用某些數據時,可以在getDefaultProps() 函数中定義這個属性,然後通过{this.props.style}來進行獲取:

    • 對象或數組都會在所有實例中共享

      class CustomizableText extends Component {
         constructor(props) {
           super(props);   
             this.style = {
             };
         }
         render() {
           return (
             <Text style ={[this.props.style]} >Hello</Text>
           )
         }
       };
       CustomizableText.propTypes = {
         style: React.PropTypes.Text.isRequred,
       };
    • 新版改為以下寫法:

      constructor(props) {
         super(props);   
         this.state = {
         };
      }
  • getInitialState():

    • 當物件被調用時此方法會在寫入 DOM 之前被觸發,通常用來管理狀態的元件可以用這個方法初始化一些資料,用來初始化每個實例的state, 可以訪問到this.props

    • 當components完成render後, 可使用setState改變this.state的內容, 此時會重新render以達成動態改變畫面的效果

      this.setState({
         mykey:'my new value'
      });
    • 新版改為以下寫法:

      constructor(props) {
          super(props);   
          this.state = {
          };
       }
  • componentWillMount():

    • render被調用前最後可以修改組件state的最後機會

    • 这個时候DOM结構已经渲染了.這個時候就可以初始化其他框架的設置了,如果利用jQuery绑定事件等等.

  • render():

    • 此函數將創建虛擬DOM

    • 是唯一一個必須的方法

    • 必須滿足下面幾點:

      • render返回的並不是真正的DOM, 而是一個虛擬的表現, React將會將他與真實的DOM做對比, 來判斷是否有必要作出修改.

  • componentDidMount():

    • 當元件被寫入 DOM 之後觸發。當初始化需要操作 DOM 元素就可以用這個方法

    • 可以在這邊使用getDOMNode()

    2) Props Changes, State Changes (存在期):

  • componentWillReceiveProps(nextProps)

  • shouldComponentUpdate(nextProps, nextState)

  • componentWillUpdate(nextProps, nextState)

  • render()

  • componentDidUpdate(prevProps, prevState)

3) Unmounting (銷毀&清理期):

componentWillUnmount

reference:

1) http://andyyou.logdown.com/posts/370308
  2) http://busypeoples.github.io/post/react-component-lifecycle/
  3) https://www.kirupa.com/react/component_lifecycle.htm
  4) http://andyyou.logdown.com/posts/178998-reactjs-assembly-operation-and-life-cycle
  5) https://staminaloops.github.io/undefinedisnotafunction/understanding-react/

5.Data flow: prop vs. prop.children, state

  • prop: property的縮寫

  • 1.this.prop:

    • 指定單一個由上層元件所傳入的參數, 需寫在標籤內 (字串符)

          var Parent = React.createClass({
            render: function(){
              return(
                <div>
                  {this.props.childrenA}
                </div>
              );
            }
          });
          var Root = React.createClass({
              render: function(){
                return(
                  <Parent childrenA={ChildrenA}/>
                );
              }
          });
          React.render(<Root />, document.getElementById('app'));
  • 2.this.prop.children

    • 上層元件所傳入的參數陣列, 寫在標籤的內容中

          var Parent = React.createClass({
              render: function(){
                  return(
                    <div>
                        {this.props.children}
                    </div>
                  );
              }
          });
          var Root = React.createClass({
              render: function(){
                return(
                  <Parent >
                    <ChildrenA />
                    <ChildrenB />
                    <ChildrenC />
                  </Parent>
                );
              }  
          });
      
          React.render(<Root />, document.getElementById('app'));
  • 3.propTypes:

    • propTypes 使用來規範元件Props的型別與必需狀態

      • 當父元件沒有提供props的屬性時,可以採用getDefaultProps,

        預設props屬性的方式,讓元件使用預設的設定值,確保有props帶入。

    • React.PropTypes 的種類:

      • React.PropTypes.array // 陣列

      • React.PropTypes.bool.isRequired // Boolean 且必要。

      • React.PropTypes.func // 函式

      • React.PropTypes.number // 數字

      • React.PropTypes.object // 物件

      • React.PropTypes.string // 字串

      • React.PropTypes.node // 任何類型的: numbers, strings, elements 或者任何這種類型的陣列

      • React.PropTypes.element // React 元素

      • React.PropTypes.instanceOf(XXX) // 某種XXX類別的實體

      • React.PropTypes.oneOf(['foo', 'bar']) // 其中一個字串

      • React.PropTypes.oneOfType([React.PropTypes.string,

      • React.PropTypes.array]) // 其中一種格式類型

      • React.PropTypes.arrayOf(React.PropTypes.string) // 某種類型的陣列(字串類型)

      • React.PropTypes.objectOf(React.PropTypes.string) // 具有某種屬性類型的物件(字串類型)

      • React.PropTypes.shape({ // 是否符合指定格式的物件

        color: React.PropTypes.string,

        fontSize: React.PropTypes.number

        });

      • React.PropTypes.any.isRequired // 可以是任何格式,且必要。

  • state與props的差別是在於state只存在組件的內部

  • this.state -> 同層物件

    • 1.this.setState

      setState is done to 'set' the state of a value, even if its already set

      in the 'getInitialState' function.

    • 2.this.replaceState

      The replaceState() method is for when you want to clear out the values

      already in state, and add new ones.

  • this.props -> 上層物件

6. Layout, Event Handing

  • 1.將影像佈滿背景:

     var styles = StyleSheet.create({
      backgroundImage: {
        flex: 1,
        alignSelf: 'stretch',
        width: null,
      }
     });

7.Using JQuery in React

  • 1.Install Jquery

    npm install jquery --save
  • 2.Use AJAX by JQuery

    • 1.Import:

      import $ from 'jquery';
    • 2.Call AJAX API

      componentDidMount() {  
        this.serverRequest = $.get("https://jenhsuanhsieh.ddns.net:3000/gitbook", function (result) {})  
       }  
       componentWillUnmount\(\) {  
          this.serverRequest.abort\(\);  
       }
  • 3.webpack.config.js

      module: {  
        plugins: [  
         new webpack.ProvidePlugin({  
            $: "jquery",  
           jQuery: "jquery"  
          })  
       ]  
      }

8.Using D3.js in React

  • 1.install d3

      npm install d3 --save
  • 2.Import d3

      import d3 from 'd3';
  • 3.Basic structure could contain: constuctor(), componentDidMount(), componentWillReceiveProps(), render()

    • 1.put svg and its d3 components in render(), such as Arc, circle.

    • 2.put parameters that you would like to pass to render() by this.props and this.state, you can initial them in constructor()

    • 3.After components mounted, you can do something to change UI or event trigger something, do in componentDidMount()

     class WsDonut extends Component {
     constructor(props) {
      super(props);
      this.state = {
      };
     }

     componentDidMount() {
     //do something after render was done
       d3.select("svg").selectAll("path")
       .on("mouseover", function(d,i) {
        // mouse over handler
       }.bind(this) )
       .on("mouseout", function(d,i) {
        //mouse out handler
       }.bind(this) )
       .on("mouseclick", function(d,i) {
        //mouse click handeler
       }.bind(this) );
     }
     componentWillReceiveProps(){
     //do something when props was changed
     }

     render() {
       return (
       <svg width={} height={} >
         <g>
          <Arc
           path={}{}
           stroke={}
           fill={}
           width={}
           height={}
           key={} />
        <circle
           r="6"
           cx={} 
           cy={}
           fill={}
           key={}/>
      </g>
      <text
       x={}
       y={}>
      </text>
    </svg>
   );
  }

9.Dynamic Routing

  • 1.Introduction

    • 要完成SPA (Single Page Application)不可或缺的就是dynamic routing, 在React的生態系中可以使用react-route這個套件來協助我們完成.

  • 2.Install package

    npm install react-route --save
    • Main Entry

      • 定義routing rule及URL的宣告方式

        • 1.import package

          import {
            Router,
            Route,
            browserHistory
          } from 'react-router'
        • 2.宣告routing的components

          • 舉例來說, 假設我們有三個Page需要做routing, 便需要定義在Main Entry中

            • 1.Router, History

            • 2.Route

              render((
              <Router history={browserHistory}>
                  <Route path="/" component={Page1}/>
                  <Route path="/Page2" component={Page2}/>
                  <Route path="/Page3" component={Page3}/>  
              </Router>

              ), document.getElementById('container'))

    • 導覽列 (nav bar或button)

      • 連結到routing components

Previous3.functionNext4.1.Introduction

Last updated 5 years ago

Was this helpful?

reference:

3.Setting

http://stackoverflow.com/questions/23293626/setstate-vs-replacestate-in-react-js
http://jamestw.logdown.com/posts/257890-257890-reactjs-prop