一、Hooks
1. React Hook/Hooks是什麼?
2. 三個常用的Hook
3. State Hook
4. Effect Hook
5. Ref Hook
6.代碼
1 import React from 'react' 2 import ReactDOM from 'react-dom' 3 4 //類式組件 5 /* class Demo extends React.Component { 6 7 state = {count:0} 8 9 myRef = React.createRef() 10 11 add = ()=>{ 12 this.setState(state => ({count:state.count+1})) 13 } 14 15 unmount = ()=>{ 16 ReactDOM.unmountComponentAtNode(document.getElementById('root')) 17 } 18 19 show = ()=>{ 20 alert(this.myRef.current.value) 21 } 22 23 componentDidMount(){ 24 this.timer = setInterval(()=>{ 25 this.setState( state => ({count:state.count+1})) 26 },1000) 27 } 28 29 componentWillUnmount(){ 30 clearInterval(this.timer) 31 } 32 33 render() { 34 return ( 35 <div> 36 <input type="text" ref={this.myRef}/> 37 <h2>當前求和爲{this.state.count}</h2> 38 <button onClick={this.add}>點我+1</button> 39 <button onClick={this.unmount}>卸載組件</button> 40 <button onClick={this.show}>點擊提示數據</button> 41 </div> 42 ) 43 } 44 } */ 45 46 function Demo(){ 47 //console.log('Demo'); 48 49 const [count,setCount] = React.useState(0) 50 const myRef = React.useRef() 51 52 React.useEffect(()=>{ 53 let timer = setInterval(()=>{ 54 setCount(count => count+1 ) 55 },1000) 56 return ()=>{ 57 clearInterval(timer) 58 } 59 },[]) 60 61 //加的回調 62 function add(){ 63 //setCount(count+1) //第一種寫法 64 setCount(count => count+1 ) 65 } 66 67 //提示輸入的回調 68 function show(){ 69 alert(myRef.current.value) 70 } 71 72 //卸載組件的回調 73 function unmount(){ 74 ReactDOM.unmountComponentAtNode(document.getElementById('root')) 75 } 76 77 return ( 78 <div> 79 <input type="text" ref={myRef}/> 80 <h2>當前求和爲:{count}</h2> 81 <button onClick={add}>點我+1</button> 82 <button onClick={unmount}>卸載組件</button> 83 <button onClick={show}>點我提示數據</button> 84 </div> 85 ) 86 } 87 88 export default Demo
二、Fragment
1.作用:可以不用必須有一個真實的DOM根標籤了
2.代碼
1 import React, { Component,Fragment } from 'react' 2 3 export default class Demo extends Component { 4 render() { 5 return ( 6 <Fragment key={1}> 7 <input type="text"/> 8 <input type="text"/> 9 </Fragment> 10 ) 11 } 12 }