在上一節(jié)中,我們講到了React組件,說了如何使用ES6類創(chuàng)建一個(gè)React組件并在其他的地方使用它。這一節(jié)我們將講到React組件的兩大靈魂——props和state。
props
不知道大家還記不記得xml標(biāo)簽中的屬性,就像這樣:
<class id="1"> <student id="1">John Kindem</student> <student id="2">Alick Ice</student></class>
這樣一個(gè)xml文件表達(dá)的意思是1班有兩個(gè)學(xué)生,學(xué)號(hào)為1的學(xué)生名字為John Kindem,學(xué)號(hào)為2的學(xué)生名字為Alick Ice,其中id就是屬性,你可以把它看做一個(gè)常量,它是只讀的。
html繼承自xml,而JSX從莫種意義上又是html和js的擴(kuò)展,屬性的概念自然得到了傳承。
在React中,我們使用props這一概念向React組件傳遞只讀的值,就像這樣:
// 假設(shè)我們已經(jīng)自定義了一個(gè)叫Hello的組件ReactDom.render(  <Hello firstName={'John'} lastName={'Kindem'}/>,  document.getElementById('root'));在調(diào)用React組件的時(shí)候,我們可以像上面一樣向組件傳遞一些常量,以便組件在內(nèi)部調(diào)用。而調(diào)用的方法,就像下面這樣:
class Hello extends React.Component {  constructor(props) {    super(props);  }  render() {    return (      <div>        <h1>Hello, {this.props.firstName + ' ' + this.props.lastName}</h1>      </div>    );  }}ReactDom.render(  <Hello firstName={'John'} lastName={'Kindem'}/>,  document.getElementById('root'));在組件內(nèi)部獲取傳遞過來的props,只需要使用this.props對(duì)象即可,但是在使用之前,記得復(fù)寫組件的構(gòu)造函數(shù),并且接受props的值以調(diào)用父類構(gòu)造。
當(dāng)然,props也能夠設(shè)置默認(rèn)值,向下面這樣:
class Hello extends React.Component {  constructor(props) {    super(props);  }  static defaultProps = {    firstName: 'John',    lastName: 'Kindem'  };  render() {    return (      <div>        <h1>Hello, {this.props.firstName + ' ' + this.props.lastName}</h1>      </div>    );  }}ReactDom.render(  <Hello/>,  document.getElementById('root'));只需在ES6類中聲明一個(gè)static的props默認(rèn)值即可,運(yùn)行效果和上面一樣。
props沒有多復(fù)雜,稍微練習(xí)即可習(xí)得。
state、組件生命周期
你可能回想,如果我想在React組件中添加動(dòng)態(tài)效果怎么辦?目前學(xué)過的知識(shí)好像無法解決這一問題。
這一問題需要使用React組件的state來解決,state即狀態(tài)的意思,在React中,所有會(huì)變化的控制變量都應(yīng)該放入state,每當(dāng)state中的內(nèi)容變化時(shí),頁面的相應(yīng)組件將會(huì)被重新渲染,另外,state完全是組件內(nèi)部的東西,外部無法向內(nèi)部傳遞state,也無法直接改變state的值。
先來舉一個(gè)例子:
import React from 'react';import ReactDom from 'react-dom';class Time extends React.Component {  constructor(props) {    super(props);    // 初始化state    this.state = {      hour: 0,      minute: 0,      second: 0    }  }  componentDidMount() {    this.interval = setInterval(() => this.tick(), 1000);  }  componentWillUnmount() {    clearInterval(this.interval);  }  tick() {    // 計(jì)算新時(shí)間    let newSecond, newMinute, newHour;    let carryMinute = 0, carryHour = 0;    newSecond = this.state.second + 1;    if (newSecond > 59) {      carryMinute = 1;      newSecond -= 60;    }    newMinute = this.state.minute + carryMinute;    if (newMinute > 59) {      carryHour = 1;      newMinute -= 60;    }    newHour = this.state.hour + carryHour;    if (newHour > 59) newHour -= 60;    // 設(shè)置新狀態(tài)    this.setState({      hour: newHour,      minute: newMinute,      second: newSecond    });  }  render() {    return (      <div>        <h1>current time: {this.state.hour + ':' + this.state.minute + ':' + this.state.second}</h1>      </div>    );  }}ReactDom.render(  <Time/>,  document.getElementById('root'));這樣就完成了一個(gè)計(jì)數(shù)器,數(shù)值一秒鐘變化一次,來講解一下代碼:首先,state的初始化是在構(gòu)造函數(shù)中,像這樣:
constructor(props) {  super(props);  // 在這初始化state  this.state = {    ...  }}而改變state是使用React組件基類中的一個(gè)自帶函數(shù):
this.setState({  ...});使用這個(gè)函數(shù)之前一定要注意this的作用域,箭頭函數(shù)中的this指向外部this,而普通函數(shù)中的this指向函數(shù)本身。
另外,這里使用到了兩個(gè)React組件的生命周期回調(diào):
componentDidMount() {  // React組件被加載到dom中的時(shí)候被調(diào)用  ...}componentWillUnmount() {  // React組件從dom中卸載的時(shí)候被調(diào)用  ...}所以這樣一下上面的計(jì)時(shí)器代碼應(yīng)該就不是什么難事了,在React組件被加載到dom中的時(shí)候設(shè)置一個(gè)計(jì)時(shí)器,每秒鐘更新一次state,state更新的同時(shí)頁面中的組件將會(huì)被重新渲染,而當(dāng)組件被卸載的時(shí)候,則需要清除定時(shí)器,就那么簡單。
不過React對(duì)于state的更新頻率,有一個(gè)最大的限度,超過這個(gè)限度則會(huì)導(dǎo)致頁面渲染的性能下降,大家需要注意不要在高頻函數(shù)中使用setState。
這一節(jié)React輕松入門就到這了,下一節(jié),我將會(huì)為大家介紹React組件的事件處理。如果覺得文章有幫助,請(qǐng)關(guān)注我,我會(huì)持續(xù)更新,為大家獻(xiàn)上更好更優(yōu)質(zhì)的文章!
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答