Hook的寫法,可以把Class的寫法改成純函式行表達,把React變成更純粹,更乾淨,但只適合用於比較不複雜的Component來寫。
原本
class App extends React.Component { constructor(props) { super(props); this.state = { name: "湯姆貓" }; } render() { return ( <div> {this.state.name} <button onClick={() => this.setState({ name: "壞貓咪" })}>按我</button> </div> ); } }
改寫
const App = () => { const [name, setName] = useState("湯姆貓"); return ( <div> {name} <button onClick={() => setName("壞貓咪")}>按我</button> </div> ); };
合體
import React, { useState } from "react"; import ReactDOM from "react-dom"; class App extends React.Component { constructor(props) { super(props); this.state = { name: "湯姆貓" }; } render() { return ( <div> {this.state.name} <button onClick={() => this.setState({ name: "壞貓咪" })}>按我</button> <UseStateHook /> </div> ); } } const UseStateHook = () => { const [name, setName] = useState("傑立鼠"); return ( <div> {name} <button onClick={() => setName("臭老鼠")}>按我</button> </div> ); }; ReactDOM.render(<App />, document.getElementById("app"));
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記