結論:需要根據state進行渲染時,使用React.Component;用不到state時,可以直接寫函數組件。
Function 函數組件:可以接收入參(props),通過return返回dom結構。
function Hello(props) { return <h1>Hello, {props.name}!</h1>; } ReactDOM.render( <Hello name="Jack" />, document.getElementById('root') );
React.Component 是一個class(類),不止可以接收props,也支持state,還包含了生命周期函數,在render函數內返回dom結構。
class Hello extends React.Component { constructor(props) { super(props); this.state = { myname:"" }; } componentDidMount(){ this.setState({ myname:"baby" }) } render() { return ( <div> <h1>Hello, {this.props.name}!</h1> <h1>I am {this.state.myname}</h1> </div> ); } } ReactDOM.render( <Hello name="Jack" />, document.getElementById('root') );
Hook 是React的新特性,通過 useState 和 EffectState 方法,讓函數組件也支持了state。
// Hook寫法 import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } // 對應Class寫法 class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } componentDidMount() { document.title = `You clicked ${this.state.count} times`; } componentDidUpdate() { document.title = `You clicked ${this.state.count} times`; } render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button> </div> ); } }