Web_Advance
  • 本書簡介
  • Node.js 部分
    • Node 版本管理
    • 使用NPM
      • Yarn
    • 開始Node
    • Worker Thread
    • REPL
    • TCP
    • path
    • Cluster and Child_process
    • assert (自訂拋出的錯誤)
    • Stream(流)
    • util (工具類)
    • EventEmitter
    • fs 文件操作
    • Buffer
      • Binary Diff
      • 查看 Binary 檔案內容
    • Process (進程)
    • 錯誤處理
  • OS
  • Async Hook
  • TCP
  • HTTP
    • 有關爬蟲
    • HTTP/2
    • HTTP Protocal
  • HTTPS
    • HTTPS 流程
    • SSL pinning
    • HTTPS 封包解密
    • 建立自簽發 HTTPS 證書
    • 幫網站加上HTTPS
    • HTTPS原理
  • Crypto加密
  • 有關繼承
  • JS 基本
    • JavaScript 迴圈與異步處理
  • 使用 Express
    • 上傳檔案
    • 圖片伺服器
    • 簡單範例
  • 使用 Nest.js
  • 使用MongoDB
    • 設置帳戶登入權限
    • Mongoose 框架
    • 進階Mongo
    • 基本環境操作
    • MongoDB Sharding
  • 使用MySQL
    • Schema 架構設計
    • SQL 語法
    • SQL Procedure
    • Node.js 操作 MySQL
    • 使用 Sequelize
      • DB Migration
      • function
  • 使用PostgreSQL
    • 常見問題
    • replica
    • 基本指令
    • 使用Node.js操控pg
    • SQL 基礎
  • 使用TypeORM
  • RethinkDB
  • CSS 深度探討
    • Width, Height
  • React
    • 第三方組件
      • Formik
    • styled component
    • propTypes
    • React webpack 部署
    • React util
    • 寫component並且publish
    • create-react-app
    • Context API
    • i18n
    • Server side render
    • Next.js教學
    • Higher order component 與 Recompose
    • component 間 互相存取
    • React hook
  • React router
    • 自己寫一個Router
  • Redux
    • Redux Toolkit
    • 小技巧
    • Redux sagas
    • compose
  • React Native
    • adb
    • InApp Billing
    • Icon
    • SVG
    • Firebase
      • Phone Auth
    • 自動化測試
    • Splash screen
    • Websocket
    • Googla OAuth
      • iOS
      • Android
    • Facebook OAuth
      • iOS
      • Android
    • IOS
    • 第三方組件
      • Auth Code Input
      • Country Code Picker
      • onboarding screen
      • Toast
    • ESlint
    • Push notification
    • Android 上架步驟
    • Expo
    • router
      • react-navigation套件
    • 原生組件
      • RefreshControl
      • Modal
      • Alert
      • button
      • KeyboardAvoidingView
      • Drawer
      • Image
    • 限制螢幕垂直與水平
    • NativeBase UI
    • Debug
    • 常見問題
    • Network
    • 硬體操作
      • 隱藏鍵盤
      • 地理位置
      • 相機與圖片庫存取
    • Async Storage
    • Animation
    • Admob
  • JS 模組化
  • 使用 Webpack
  • 使用 Babel
  • JWT Token
  • ES6 ES7 ES8
    • Array method
    • ES8 Async
    • ES6 Proxy
    • ES6 Object
    • ES6 Arrow function
    • ES6 Promise
    • ES6 Symbol
    • ES6 Generator
    • ES6 Set,Map
    • ES6 Class
  • 模板引擎
    • Mustache
    • Handlebars.js
    • EJS
  • ESLint
  • 部屬到OpenShift
  • OpenStack
  • OAuth
    • Twitter OAuth
    • Google authenticator
    • facebook oauth
      • facebook like ,share
    • google oauth
  • Redis
  • 做一個簡單的markdown editor
  • Websocket
    • WebSocket 相關 Protocol
  • Sublime 安裝套件
  • Google api
    • Cloud Run
    • speech api
    • place autocomplete
    • Geocode
    • Map
      • React map
    • vision api
    • Google-recaptcha
    • Google sheet
  • Instagram API
  • Markdown 與 code pretty js
  • HTML5
    • IntersectionObserver
    • HTML5 audio
    • HTML5 Video 與 WebRTC
      • WebRTC 進階
      • WebEX API
    • HTML5 IndexedDB
  • Google Cloud Platform (GCP)
    • Cloud Storage
    • Cloud storage 串接 Cloud CDN
  • Vim 編輯器
  • 使用nginx
    • config
  • Unix 實用指令
    • 新 VPS 安裝流程
    • Ubuntu 22 安裝
    • Shell Script 教學
  • Git 實用指令
    • Git hook
    • 加上 SSH-key 到 GitHub
    • GPG簽名
  • SSH 實用指令
  • 有關Fetch與axios與跨域請求
  • 圖片上傳相關
    • imgur API
  • JS 格式轉換
  • js trick
  • AWS
    • AWS EBS
    • AWS HTTPS 憑證
    • AWS Cloudfront、ELB、ACL
    • AWS Athena
    • AWS CloudWatch、SNS
    • AWS RDS
    • AWS lambda
      • 範例
      • 加上權限控管
    • AWS S3
    • AWS DynamoDB
      • 結合Lambda
    • 快速把 EC2 串上 AWS Cloudfront CDN
    • AWS 證照相關
  • 有關日期Date
  • VS code 編輯器
    • VSCode 外掛 Plugin
  • CI with Gitlab&Jenkins
  • API 測試
    • Postman
      • 設置 Postman 環境變數
    • API Blueprint
    • swagger
      • 註解寫在Code內生成swagger UI
  • Javascript 實用Lib
  • 遠端寫程式
  • Quicktime錄影注意事項
  • Web開發進階Bug
  • Web壓力測試
  • LineBot
  • PM2部署
  • i18n
  • VPN
  • Protocol Buffers
  • Docker教學
    • LXC LXD
    • Docker Compose
    • Docker 原理
    • Docker 指令
  • E2E Testing
    • Cypress
    • PlayWright
    • Puppeteer 與其他 UI 測試工具
  • Unit Test (Jest & enzyme)
    • React Testing Library
    • mocha
  • Cassandra
    • cluster
  • Distribute Web
    • Dat project
    • IPFS project
  • Cluster and Child_process
  • 打包應用程式
  • Java
    • 使用gradle結合docker
  • Debug 頁面
  • Proxy
  • Chrome extension
  • 消息系統
    • RabbitMQ
  • 金流串接
    • Paypal
    • spgateway智富通
    • Stripe 串接
  • 有關Log
  • 設定 feature flag
  • Azure
    • Face API
    • Image Analyze API
    • Azure Serverless
    • Cosmos DB
      • 使用 SDK
      • 以 RESTful 操作 DB
      • 一致性策略與 DB replicate
  • NodeBB 筆記
  • 瀏覽器快取與緩存(Etag, If-None-Match)
  • 瀏覽器快取與緩存(Expires, Last-modified, Cache-Control)
  • Node.js 第三方模組
    • OpenCV
  • Kubernetes
    • 本地測試 MiniKube
  • Ngrok 使用
  • Telegram MiniAPP 開發
  • Firebase 教學
  • 演算法筆記
  • 圖表
    • Echart
    • TradingView 圖表
    • D3
    • 熱力圖 heatmap
  • 後端緩存 Cache
  • 資料一致性
  • Web 安全機制
    • Cookie 與 LocalStorage
  • Vue
    • Element UI
    • Devtool
    • Vuex
    • Vue router
  • 相關網路協議
    • 網路 IP 基礎
    • Google Search 技巧
    • 網路診斷工具
    • IP
    • DNS
  • GitLab 與 Drone
  • SMTP、POP、IMAP
    • SendGrid
  • IPC
  • 串流服務
    • Twilio
    • Agora
  • 其他資源
  • GraphQL
  • Typescript
  • UI 相關資源
  • FFmpeg
  • Unity 遊戲開發筆記
  • Influx DB
  • Windows 相關
  • DALL·E 3
  • Coap
  • Slack API
  • 資訊安全
    • 破解 ZIP 密碼
Powered by GitBook
On this page
  • React
  • 開始使用React
  • 建立環境
  • 讓我們不用重新整理網頁
  • 第二階段
  • 為元件加入方法
  • 在class中的方法如果有this的話他會不知道this是什麼,所以要在class 的constructor中把該方法綁進來
  • 2.在class內所有的this都是指到那個class
  • Prop
  • 在元件內使用條件判斷
  • 使用React router
  • 如何寫style
  • 加上Bootstrap
  • 選取元素
  • Material UI 現在0.15後需如下使用
  • 使用server side rendering with Material UI
  • React toggle style
  • 在render方法內使用js新增component
  • findDOMNode
  • Server side rendering(使用Express)
  • Stateless component
  • #有關dangersetInnerHTML
  • Isomophic注意事項
  • <input /> 裡面的defaultValue如不顯示時 在屬性加個跟著value變動的key即可
  • Refs

Was this helpful?

Edit on GitHub

React

PreviousWidth, HeightNext第三方組件

Last updated 5 years ago

Was this helpful?

React

  1. 建議react 和react-dom相同版本才比較不會有問

  2. 如果使用create-react-app,如果套件在index.html引入須在使用套件時加上window

基礎

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
  <script src="https://fb.me/react-15.0.0.js"></script>
    <script src="https://fb.me/react-dom-15.0.0.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
    core/5.8.34/browser.min.js"></script>
</head>
<body>
    <div id="example"></div>
    <script type="text/babel">
      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
      );
    </script>

</body>
</html>
var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

ReactDOM.render(<HelloMessage name="John" />, mountNode);

使用ES6

class HelloMessage extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

ReactDOM.render(<HelloMessage name="Sebastian"/>, mountNode);

其他方法之簡單整理

class baseComponent extends React.Component{
    // 建構子
    constructor(props){
        super(props);
    }
    // ...其他公用代碼,方法等封装
}    
//定義另一類別,繼承baseComponent
class App extends baseComponent{
    // 建構子
    constructor(props){
        super(props);
    }
    // 初始化state,替代原getInitialState, 注意前面
    沒有static
    state = {
        showMenu:false
    };
    // 替代原propTypes 属性,注意前面有static,屬於靜態方法.
    static propTypes = {
        autoPlay: React.PropTypes.bool.isRequired
    }
    // 默認defaultProps,替代原getDefaultProps方法, 注意前面
    有static
    static defaultProps = {
        loading:false
    };
    // 這以用箭頭函數箭頭函數不會改變this的指向,否則函數內,
    this指的就不是當前對象了
    // React.CreatClass方式React會自動綁定this,ES6寫法不會.
    handleClick = (e)=>{
        this.setState();//
    };
    componentDidMount() {
        // React内置的周期 ,這裡要顯示所繼承父類的相同function,
        // 否則一旦父類中有封裝,子類會把和父類相同的function覆蓋,
        不會執行父類的function.
        // 但...父類如果本身沒有寫出componentDidMount,在子類
        寫出的話就會錯誤,

        if (super.componentDidMount) {
            super.componentDidMount();
        }
        // do something yourself...
    }
}

開始使用React

建立環境

npm install webpack -g

npm install nodemon -g (在更改程式時自動執行server,而forever為遇到錯誤也不會停止)

1.裡面放入package.json

{
  "name": "react-todo-list",
  "version": "1.0.0",
  "description": "A simple todo list app built with React, Redux and Webpack",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "nodemon server/server.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/kweiberth/react-todo-list.git"
  },
  "author": "Kurt Weiberth",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.4.5",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "express": "^4.13.4",
    "react": "^0.14.7",
    "react-dom": "^0.14.7",
    "webpack": "^1.12.13"
  }
}

之後輸入npm install

在根目錄下新建三個目錄

forclass
    --client
    --components
    --server
    package.json

2.接著在server目錄下新增server.js

var express = require('express');
var path = require('path');

var app = express();

app.use(express.static('./dist'));

app.use('/', function (req, res) {
    res.sendFile(path.resolve('client/index.html'));
});

var port = 3000;

app.listen(port, function(error) {
  if (error) throw error;
  console.log("Express server listening on port", port);
});

3.在client資料夾內加入index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>React Todo List</title>
</head>
<body>
  <h1>This is not a React app yet!</h1>
  <div id="app"></div>
  <script src="bundle.js"></script>
</body>
</html>

4.新增webpack 配置文件webpack.config.js

module.exports = {
  devtool: 'inline-source-map',
  entry: ['./client/client.js'],
  output: {
    path: './dist',
    filename: 'bundle.js',
    publicPath: '/'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['react', 'es2015']
        }
      }
    ]
  }
}

什麼是source map

5.在client資料夾中新增client.js

import React from 'react'
import { render } from 'react-dom'
import App from '../components/App'

render(
  <App/>,
  document.getElementById('app')
)

<App/>即為我們的react元件

6.在components資料夾中新增App.js

此即為我們第一個react元件

import React, { Component } from 'react'

class App extends Component {

  render() {
    return <div>I'm Banana!</div>
  }

}

export default App

輸入webpack --config webpack.config.js 會自動產生dist資料夾,裡面包含bundle.js檔案

之後即可重新啟動伺服器,並觀看改變 npm run serve(寫在package.json中的scripts內)

讓我們不用重新整理網頁

在package.json內加入

1.不用重新整理網頁 (讓我們不用使用webpack-dev-server也有-hot的指令)

"webpack-hot-middleware": "^2.6.4"

2.讓hot middleware知道react的class

"babel-preset-react-hmre": "^1.1.0",

以及上webpack跑在我們架設的express server上

"webpack-dev-middleware": "^1.5.1"

完整版

{
  "name": "react-todo-list",
  "version": "1.0.0",
  "description": "A simple todo list app built with React, Redux and Webpack",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "nodemon server/server.js --ignore components"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/kweiberth/react-todo-list.git"
  },
  "author": "Kurt Weiberth",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.4.5",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-preset-react-hmre": "^1.1.0",
    "express": "^4.13.4",
    "react": "^0.14.7",
    "react-dom": "^0.14.7",
    "webpack": "^1.12.13",
    "webpack-dev-middleware": "^1.5.1",
    "webpack-hot-middleware": "^2.6.4"
  }
}

npm install後

接著更改剛才server資料夾下的 server.js

var express = require('express');
var path = require('path');
var config = require('../webpack.config.js');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');

var app = express();

var compiler = webpack(config);

app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));
app.use(webpackHotMiddleware(compiler));

app.use(express.static('./dist'));

app.use('/', function (req, res) {
    res.sendFile(path.resolve('client/index.html'));
});

var port = 3000;

app.listen(port, function(error) {
  if (error) throw error;
  console.log("Express server listening on port", port);
});

現在我們可以直接用server.js去compile 我們的webpack config檔案,不用再輸入指令compile

最後因為我們剛才有用hot middle所以我們可以使用--hot去讓他自動reload網頁,但我們不想在指令輸入,所以可以把他加在webpack config內

webpack.config.js

var webpack = require('webpack');

module.exports = {
  devtool: 'inline-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './client/client.js'
  ],
  output: {
    path: require("path").resolve("./dist"),
    filename: 'bundle.js',
    publicPath: '/'
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['react', 'es2015', 'react-hmre']
        }
      }
    ]
  }
}

現在執行 npm run serve

再去更改app.js內的字,可以看到不用重新啟動伺服器,也不用按網頁的重新整理,即可更新

第二階段

開始新增其他react元件

在components下,新增一個檔案 TextDisplay.js

import React, {Component} from 'react'

class TextDisplay extend Component{

}

export default TextDisplay

上面是引用react後建造一個空的class後將他輸出

接著我們要在class內寫入東西

import React, {Component} from 'react'
//JSX要看到import了React 才可以編譯 
class TextDisplay extends Component{

    render() {
        return (
            <div>
            <div> THis is text display</div>
            <div> if we have two div we need to wrap it.</div>
            </div>

        )};

}

export default TextDisplay

使著將最外層的div刪掉,會出現錯誤,因為一個元件要有東西包住最外層。

之後讓原來的App.js引用他

import React, { Component } from 'react'

class App extends Component {

  render() {
    return (
    <div>
    <div>This is definitely a React app now!</div>
    <TextDisplay/>
    </div>
  )}

}
export default App

使用state

TextDisplay.js

import React, { Component } from 'react'


class TextInput extends Component {

  constructor() {
    super()
    this.state = {
      inputText: ' sdxt'
    }
  }



  render() {
    return (
      <div>
        <input
          type="text"
          placeholder="This is going to be text"
          value={this.state.inputText}

        />

      </div>
    )
  }

}

export default TextInput

!!記得重新整理網頁,才會作用(因為這裡是constructor)

為元件加入方法

import React, { Component } from 'react'


class TextInput extends Component {

  constructor() {
    super()
    this.state = {
      inputText: ' sdsxt'
    }
  }

 handleChange(){
     console.log("ch")
 }

  render() {
    return (
      <div>
        <input
          type="text"
          placeholder="This is going to be text"
          value={this.state.inputText}
          onChange={this.handleChange}
        />

      </div>
    )
  }

}

export default TextInput

在class中的方法如果有this的話他會不知道this是什麼,所以要在class 的constructor中把該方法綁進來

1.

import React, { Component } from 'react'


class TextInput extends Component {

  constructor() {
    super()
    this.state = {
      inputText: ' sdsxt'
    }
    this.handleChange = this.handleChange.bind(this);
  }

 handleChange(){
     this.setState({inputText:12});
 }

  render() {
    return (
      <div>
        <input
          type="text"
          placeholder="This is going to be text"
          value={this.state.inputText}
          onChange={this.handleChange}
        />

      </div>
    )
  }

}

export default TextInput

但後來發現如果想傳入參數還是要在html tag中寫bind才會傳入

2.所以另一種寫法,是直接在DOM 的onchange中綁,但官方推薦綁在constructor

onChange={this.handleChange.bind(this)}

接著在render上面寫

handleChange(){
 ...
}

3.第三種寫法(ES6的箭頭函數,最方便,因為會直接幫你綁定)

send = () => {
    console.log(this.inputFiled.value)
    let text = this.inputFiled.value;
    this.props.addTodo1(text);
  }


 <button onClick={()=>this.handleSubmit()}>Submit</button>

如要傳入事件,記得兩邊()都要傳入

<form onSubmit={(e)=>this.handleSubmit(e)}>

好處是不用再用bind

!每次改動constructor記得都要重新整理,就算有用Hot reload

完整範例:

注意其中的onclick 與 從子元件傳上來的 onclick

container

import React, { Component } from 'react'
import {connect} from 'react-redux'
import actions from '../redux/actions/todoActions.js'
import { bindActionCreators } from 'redux'
import List from '../components/List.js'

class TodoList extends Component {
  send = () => {
    let text = this.inputFiled.value;
    this.props.addTodo1(text);
  }
  itemClick = (e,id) => {
    console.log(e)
    console.log(id)
  }
  render() {
    return (
      <div>
        <input ref={(c) => this.inputFiled = c} />
        <button onClick={()=>this.send()}></button>
        <List list={this.props} itemClick={(e,id)=>this.itemClick(e,id)}>
        </List>
      </div>
    )
  }

}
function mapStateToProp(state){
    return state
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    addTodo1:actions.addTodo
  },dispatch);
}

export default connect(mapStateToProp,mapDispatchToProps)(TodoList)

component

import React from 'react'
const List = (props) => {
 let todos = Array.from(props.list.todos);
  return (
    <div>
      {todos.map( i =>
         <p key={i.id} onClick={(e)=>props.itemClick(e,i.id)}>{i.text}</p>
      )}
    </div>
  )
}

export default List;

2.在class內所有的this都是指到那個class

所以要取得onchange時input內的value必須用e.target ,因為這裡不是DOM

import React, { Component } from 'react'


class TextInput extends Component {

  constructor() {
    super()
    this.state = {
      inputText: ' sdst'
    }
    this.handleChange = this.handleChange.bind(this);
  }

 handleChange(e){
     console.log(e.target.value);
     console.log(this);
     //this.setState({inputText:12});
 }

  render() {
    return (
      <div>

        <input onChange={this.handleChange} />
      </div>
    )
  }

}

export default TextInput

Prop

即為HTML tag中的屬性

1.新增一個元件為Propest.js

import React, { Component } from 'react'

class Proptest extends Component {
    render(){
        return <div> {this.props.text}</div>
    }
}
export default Proptest

TextDisplay.js

import React, { Component } from 'react'
import Proptest from "./Proptest"

class TextInput extends Component {

  constructor() {
    super()
    this.state = {
      inputText: ' sdst'
    }
    this.handleChange = this.handleChange.bind(this);
  }

 handleChange(e){
     console.log(e.target.value);

     this.setState({inputText:e.target.value});
 }

  render() {
    return (
      <div>

        <input onChange={this.handleChange} />
        <Proptest text="123"/>
      </div>
    )
  }

}

export default TextInput

即可看到Proptest的props顯示出

2.讓子代的view啟動父代的method

Proptest.js

import React, { Component } from 'react'

class Proptest extends Component {

    constructor(){
        super()

    }


    render(){
        return( 

        <div> 
            <button onClick={this.props.deleteLetter}> </button>

        </div>
    )}
}
export default Proptest

TestDisplay.js

import React, { Component } from 'react'
import Proptest from "./Proptest"

class TextInput extends Component {

  constructor() {
    super()
    this.state = {
      inputText: ' sdst'
    }
    this.handleChange = this.handleChange.bind(this);
    this.deleteLetter = this.deleteLetter.bind(this);
  }

 handleChange(e){
     console.log(e.target.value);

     this.setState({inputText:e.target.value});
 }
 deleteLetter(){
     console.log(this);
 }

  render() {
    return (
      <div>

        <input onChange={this.handleChange} />
        <Proptest deleteLetter={this.deleteLetter}/>
      </div>
    )
  }

}

export default TextInput

進階(點擊button更改state)

import React, { Component } from 'react'
import Proptest from "./Proptest"

class TextInput extends Component {

  constructor() {
    super()
    this.state = {
      inputText: ' sdst'
    }
    this.handleChange = this.handleChange.bind(this);
    this.deleteLetter = this.deleteLetter.bind(this);
  }

 handleChange(e){
     console.log(e.target.value);

     this.setState({inputText:e.target.value});
 }
 deleteLetter(){
     this.setState({
         inputText:this.state.inputText.substring(0,this.state.inputText.length-1)
     });
 }

  render() {
    return (
      <div>

        <input    value={this.state.inputText}     onChange={this.handleChange} />
        <Proptest text={this.state.inputText} deleteLetter={this.deleteLetter}/>
      </div>
    )
  }

}

export default TextInput
import React, { Component } from 'react'

class Proptest extends Component {

    constructor(){
        super()

    }


    render(){
        return( 

        <div> 
            <p>{this.props.text}</p>
            <button onClick={this.props.deleteLetter}> </button>

        </div>
    )}
}
export default Proptest

在元件內使用條件判斷

import React, { Component } from 'react'
import Proptest from "./Proptest"



class TextInput extends Component {

  constructor() {
    super()
    this.state = {
      inputText: ' sdst'
    }
    this.handleChange = this.handleChange.bind(this);
    this.deleteLetter = this.deleteLetter.bind(this);
  }

 handleChange(e){
     console.log(e.target.value);

     this.setState({inputText:e.target.value});
 }
 deleteLetter(){
     this.setState({
         inputText:this.state.inputText.substring(0,this.state.inputText.length-1)
     });
 }






  render() {
      var checkFalse = true;
      if(checkFalse){
          checkFalse =  <Proptest text={this.state.inputText} deleteLetter={this.deleteLetter}/>;
     }else{
          checkFalse = <p>This is false</p>
      }



    return (
      <div>

        <input    value={this.state.inputText}     onChange={this.handleChange} />

        {checkFalse}

      </div>
    )
  }

}

export default TextInput

使用AJAX

1.先在server.js加上app.post的路徑

app.post('/hi',function(req,res){
    res.end("hi");
});

2.

import React, { Component } from 'react'
import Proptest from "./Proptest"



class TextInput extends Component {

  constructor() {
    super()
    this.state = {
      inputText: ' sdst'
    }
    this.handleChange = this.handleChange.bind(this);
    this.deleteLetter = this.deleteLetter.bind(this);
  }






 handleChange(e){
     console.log(e.target.value);

     this.setState({inputText:e.target.value});
 }
 deleteLetter(){
     $.ajax({
     type:"POST",
      url: "/hi",
      dataType: 'text',
      success: function(data) {
        console.log(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error("error");
      }.bind(this)
    });


     this.setState({
         inputText:this.state.inputText.substring(0,this.state.inputText.length-1)
     });
 }






  render() {
      var checkFalse = true;
      if(checkFalse){
          checkFalse =  <Proptest text={this.state.inputText} deleteLetter={this.deleteLetter}/>;
     }else{
          checkFalse = <p>This is false</p>
      }



    return (
      <div>

        <input    value={this.state.inputText}     onChange={this.handleChange} />

        {checkFalse}

      </div>
    )
  }

}

export default TextInput

使用React router

clone後到branch master開始進行

  1. npm install react-router

之後開啟client.js

改為下面,看是否仍正常啟動

import React from 'react'
import { render } from 'react-dom'
import App from '../components/App'
import { Router, Route, hashHistory } from 'react-router'

render(( 
    <Router history={hashHistory}>
     <Route path="/" component={App}/>
    </Router> 
  ),document.getElementById('app'))

再改為下面看看

import React from 'react'
import { render } from 'react-dom'
import App from '../components/App'
import Proptest from '../components/Proptest'
import { Router, Route, hashHistory } from 'react-router'

render(( 
    <Router history={hashHistory}>
    <Route path="/" component={App}/>
     <Route path="/about" component={Proptest}/>
    </Router> 
  ),document.getElementById('app'))

即可看到,元件的切換

(發現頁面切換元件很快速,我們以前要做到這樣必須用AJAX,或模板引擎內的動態compile(一樣是AJAX加載), 但React沒用到ajax,完全都在client端計算更改的virtual DOM後更新到DOM上)

接著可到webpack那章,加上commonchunk plugin,加速我們每次網頁重新整理的速度

如何寫style

個人習慣方式為:

1.創一個style資料夾

2.每個component有對應名稱的css檔案

3.之後全部@import到index.css內

4.於server設定app.use(express.static('./style'));

5.引入到index.html

<link rel=stylesheet type="text/css" href="../style.css">

加上Bootstrap

雖然有react-bootstrap,但我們也可用原本的方式

在client.js加上

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

之後在用這個轉換網站轉換後貼上即可,記得外面要包著div

選取元素

在元素內放入下面的property

ref={(c) => this._input = c}

再用this._input即可選定該元素

或是

<input ref="myInput" />

var input = this.refs.myInput;
var inputValue = input.value;

Style React

一般寫法:

把style放在物件裡面

<button style={style.submit} onClick={()=>this.handleSubmit()}>Submit</button>

  var style = {
  submit:{background:"green"}
}

使用其他庫

1.Radium

1.import Radium from 'radium'

2.export default Radium(TodoInput) //class名稱

3.var style = {
  submit:{
        ':hover': {
              backgroundColor: 'red'
            }
  }
}

2.Material-ui

npm install material-ui

都是個別引入

import RaisedButton from 'material-ui/lib/raised-button';

 <RaisedButton label="Submit"onClick={()=>this.handleSubmit()} />

PS:如果使用click相關的元件沒反應的話

npm install react-tap-event-plugin

import injectTapEventPlugin from 'react-tap-event-plugin';

  constructor(props) {
    super(props);

    injectTapEventPlugin();
  }

Material UI 現在0.15後需如下使用

1.加入Mui 的context

2.injectTapEventPlugin();

import React from 'react';
import ReactDOM from 'react-dom';
import { render } from 'react-dom'
import root from './root.js'
import {Provider} from 'react-redux'
import {configureStore} from '../redux/store'
import {Router, browserHistory, Route} from 'react-router';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
const initialState = window.__PRELOADED_STATE__;
injectTapEventPlugin();
const store = configureStore(initialState);

ReactDOM.render(
    <Provider store={store}>
        <MuiThemeProvider>
        <Router history={browserHistory} routes={root} />
        </MuiThemeProvider>
    </Provider>
,document.getElementById('app')
)

使用server side rendering with Material UI

一樣加入context和injectTapEventPlugin

var express = require('express');
var path = require('path');
var config = require('../../webpack.config.js');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');

import React from 'react';
import {renderToString} from 'react-dom/server';
import {RouterContext, match, createRoutes} from 'react-router';
import root from '../client/root.js';
import {Provider} from 'react-redux'
import {configureStore} from '../redux/store'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
const routes = createRoutes(root);


var app = express();

var compiler = webpack(config);

app.use(webpackDevMiddleware(compiler, {noInfo:true,publicPath: config.output.publicPath}));
app.use(webpackHotMiddleware(compiler));
app.use(express.static('./dist'));


app.post('/ajax',function(req,res){

    res.end("success");
})

let initialState = {
        todos:[{
            id:0,
            completed: false,
            text:'initial for demo'
        }]
}


const store = configureStore(initialState);


app.get('*', (req, res) => {
    const muiTheme = getMuiTheme({
      userAgent: req.headers['user-agent'],
    });
  match({routes, location: req.url}, (error, redirectLocation, renderProps) => {
    if (error) {
      res.status(500).send(error.message);
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if (renderProps) {
      const content = renderToString(
                <Provider store={store}>
                  <MuiThemeProvider muiTheme={muiTheme}>
                      <RouterContext {...renderProps} />
                  </MuiThemeProvider>
                </Provider>
            );
      let state = store.getState();
      let page = renderFullPage(content, state);
      return res.status(200).send(page);
    } else {
      res.status(404).send('Not Found');
    }
  });
});

const renderFullPage = (html, preloadedState) => (`
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>React Todo List</title>
</head>
<body>
  <div id="app">${html}</div>
  <script>
  window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\x3c')}
   </script>
  <script src="vendor.bundle.js"></script>
  <script src="bundle.js"></script>
</body>
</html>
`
);

var port = 3000;

app.listen(port, function(error) {
  if (error) throw error;
  console.log("Express server listening on port", port);
});

React toggle style

如何在點擊時切換style呢

1

<div className={"flipper" + (this.props.flipped ? " flipped" : "")}>

假設如上範例,可以先寫出,一個className的名稱的決定是由其於父組件上的prop決定

之後其父組件使用state來設定其他子組件的prop

render: function() {
        return <div>
            <Flipper flipped={this.state.flipped} orientation="horizontal" />
            <Flipper flipped={this.state.flipped} orientation="vertical" />

            <div className="button-container">
                <button onClick={this.flip}>Flip!</button>
            </div>
        </div>;

所以點擊時會觸發下面這個函式

flip: function() {
        this.setState({ flipped: !this.state.flipped });
    },

在render方法內使用js新增component

ex:

render (){
<div>
  {addth}
</div>
}

在這裡addth可以是兩種寫法

1.一個是直接return出完整的dom element

2.或是把每個dom element放入array中

['<th>some<th>','<th>some<th>']

第二種方法即是常見的使用map放入的技巧

findDOMNode

之前版本的getDOMNode已經拿掉

可如下使用findDOMNode

findDOMNode(this.refs.chart)

Server side rendering(使用Express)

參考此repo

Stateless component

相對於使用class,使用 const = function 的方式會提升效能

但其不可使用lifecycle跟state,ref

需要props傳入

使用ref需於parent的class用div寫上ref在於其內引入stateless component ,之後再用this.refs.cir1.children[0]方式取得子節點

範例:

clickCircle = (e) => {
    this.refs.cir1.children[0].style.background='red';
  }

  <div ref='cir1' key={1} onClick={(e) => this.clickCircle(e)} style={styles.circleContainer}>
    <TwoCircle />
    <div style={styles.p}>粉絲註冊點帳戶</div>
    <div style={styles.number}>6.69</div>
  </div>

#有關dangersetInnerHTML

dangerouslySetInnerHTML={{__html: }}

類似上面格式,但記得,其雖然可直接接受html tag傳入或是special char但是如果是 html tag 的special char只會轉為html tag的字串型態,如果想要他從special char直接轉為dom必須先另外寫decode function

ex:

decodeEntities = () => {
  // this prevents any overhead from creating the object each time
  var element = document.createElement('div');

  function decodeHTMLEntities (str) {
    if(str && typeof str === 'string') {
      // strip script/html tags
      str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
      str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
      element.innerHTML = str;
      str = element.textContent;
      element.textContent = '';
    }

    return str;
  }

  return decodeHTMLEntities;
};

之後再用

<div dangerouslySetInnerHTML={{__html: (this.decodeEntities())(this.state.msgContent)}} style={styles.p1}></div>

Isomophic注意事項

因為client的code會在server也跑一次

所以如果需要用到css要如下寫,注意不可用import因為會出現impoort必須在top的錯誤

if(typeof document !== 'undefined') {
  require ('./index.css');
}

<input /> 裡面的defaultValue如不顯示時 在屬性加個跟著value變動的key即可

<input key={this.state.detailName} defaultValue={this.state.detailName} className="descInput" />

Refs

  constructor(props) {
    super(props);
    this.mapRef = React.createRef();
  }
  componentDidMount() {
    console.log(this.mapRef.current);
  }

更多有關ES5 react to ES6 or ES7

有關class用法

可以看chrome dev tool 裡的setting即有此選項

參考:

到路徑

參考:

https://github.com/facebook/react/issues/8588#issuecomment-267596448
http://cheng.logdown.com/posts/2015/09/29/converting-es5-react-to-es6
http://bbs.reactnative.cn/topic/15/react-react-native-%E7%9A%84es5-es6%E5%86%99%E6%B3%95%E5%AF%B9%E7%85%A7%E8%A1%A8
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
http://es6.ruanyifeng.com/#docs/class
https://gist.github.com/sebmarkbage/d7bce729f38730399d28
http://www.ruanyifeng.com/blog/2013/01/javascript_source_map.html
http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html
https://github.com/EasonWang01/react-tutorial
http://localhost:3000/#/about
http://facebook.github.io/react/html-jsx.html
http://stack.formidable.com/radium/
http://www.material-ui.com/#/customization/inline-styles
https://github.com/callemall/material-ui#react-tap-event-plugin
https://github.com/EasonWang01/React-router-Redux-isomorphic-Boilerplate
https://reactjs.org/docs/refs-and-the-dom.html