定義元件
元件定義有兩種方式,函數定義和類定義
函數定義元件
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } const element = <Welcome name="Sara" />; ReactDOM.render( element, document.getElementById('root') );
類定義元件
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } } ReactDOM.render( <Welcome name="kevin" />, document.getElementById('root') );
警告:
元件的傳回值隻能有一個根元素。如果ReactDOM.render方法渲染元件裡包含多個同級别的元件,需要用一個DIV将其他元件包裹
類定義元件有局部狀态和生命周期鈎子事件
通常類的狀态是在類的構造函數中聲明的
class Clock extends React.Component { constructor(props) { super(props);//隻要類元件聲明了構造函數就必須先調用父類的構造函數 this.state = {date: new Date()}; } //更新狀态 this.setState({ date: new Date() }); }
如果你不在 render() 中使用某些東西,它就不應該在狀态中
鈎子函數
componentDidMount(當元件插入到DOM中觸發)
componentWillUnmount(當元件移出DOM中後觸發)
正确使用狀态
1.不要直接更新狀态,而是通過setState方法
// Wrong this.state.comment = 'Hello'; // Correct this.setState({comment: 'Hello'});
2.狀态的更新可能是異步的,你不應該依靠它們的值來計算下一個狀态
// Wrong this.setState({ counter: this.state.counter + this.props.increment, }); 當要被更新的狀态依賴于props或它自身時,setState需要傳遞一個方法作為參數,第一個參數為它的前一個狀态的值,第二個參數為props對象 // Correct this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));