Hook 是 React 16.8 的新增特性。它能夠讓你在不編寫 class 的狀況下使用 state 以及其餘的 React 特性。css
React 是支持函數式編程的可是徹底的函數式編程在這以前還沒法作到。html
好比須要用到 state 的時候就不能用純函數組件,必須使用 class 來聲明組件。node
useState 能夠讓咱們在不使用 class 的狀況下編寫有狀態組件。react
例如:webpack
// 引入 React 以及 useState
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
function App() {
// 'Hello World!' 是一個名爲 text 的常量 (Model) 咱們指望由它獲得的是 <div>Hello World!</div> (View)。
// setText 是修改 text 的惟一方式 text 一旦被修改 意味着對應的 View 也就隨之變化。
const [text, setText] = useState('Hello World!');
let inputText = '';
return (
<div> <div>{text}</div> <input onInput={(event)=>{inputText = event.target.value}}/> <button onClick={()=>{ setText(inputText) }}>Change text</button> </div> ) } ReactDOM.render(<App/>, document.getElementById('root')) 複製代碼
運行效果:git
在線瀏覽:github
全局環境npm
下載nodejs編程
使用 npm 全局安裝 webpack-cli
sudo npm i webpack-cli -g
複製代碼
sudo npm i webpack webpack-dev-server -g
複製代碼
{
"devDependencies": {
"@babel/core": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"css-loader": "^3.2.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^1.0.0",
"webpack": "^4.39.3",
"webpack-cli": "^3.3.7",
"webpack-dev-server": "^3.8.0"
},
"dependencies": {
"react": "^16.9.0",
"react-dom": "^16.9.0"
}
}
複製代碼
npm i @babel/core @babel/preset-env @babel/preset-react babel-loader css-loader html-webpack-plugin style-loader webpack webpack-cli webpack-dev-server -D
複製代碼
npm i react react-dom -S
複製代碼
app.jsx
import React, {/* Your code */} from 'react';
import ReactDOM from 'react-dom';
function App() {
/* Your code */
return (
<div> { /* Your code */ } </div>
)
}
ReactDOM.render(<App/>, document.getElementById('root'))
複製代碼
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
複製代碼
const path = require('path')
const resolve = dir => path.resolve(__dirname,dir)
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry:'./app.jsx',
output:{
path: resolve('dist'),
filename: 'bundle.js'
},
module:{
rules:[
{
test: /\.jsx?$/,
use:[
{
loader:'babel-loader',
options:{
presets:[
'@babel/env',
'@babel/react'
]
}
}
]
},
{
test: /\.html$/,
use:['html-loader']
},
{
test: /\.css$/,
use:['style-loader','css-loader']
},
{
test: /\.(png|jpe?g|gif|svg|mp4|webm|ogg|mp3|wav|flac|aac|woff2?|eot|ttf|otf)/,
use:[{
loader:'url-loader'
options:{
limit:10000
}
}]
}
],
},
devServer:{
contentBase:__dirname,
port:3000,
open:'http://localhost:3000',
},
plugins:[
new HtmlWebpackPlugin({
template:'./index.html'
})
]
}
複製代碼
(完)