React(JSX 語法)

一、JSX 語法

1.在 JSX 中嵌入表達(dá)式:
在 JSX 中嵌入表達(dá)式,必須用{}將表達(dá)式括起來。

var element = <h1>Hello, world!</h1>;

<h1> Hello { 1 + 3 }</h1>;

2.JSX 中為 element 指定屬性值。

  • 通過字符串的形式
  • 通過{表達(dá)式}的形式

二、函數(shù)式組件

定義一個(gè)函數(shù)式組件:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

使用:

<Welcome name = "world"/>

三、類組件

class Welcome extends React.Component{
    render(){
        return(
            <h1>Hello, {props.name}</h1>;
            );
    }
}

使用:

<Welcome name = "world"/>

對(duì)比:
函數(shù)式組件和類組件的名稱首字母必須大寫。所有組件的首字母都是大寫的。元素是小寫。
函數(shù)式組件的函數(shù)是純函數(shù)。
函數(shù)式組件沒有 state狀態(tài)機(jī)變量,渲染的內(nèi)容只能靠 props 來決定。

純函數(shù):相同的輸入一定得到相同的輸出。

四、狀態(tài)機(jī)變量 state 的正確使用

1、取值

this.state.comment;

2、修改

this.setState({comment:"Hello"});

不能直接修改:

this.state.comment = "Hello";

直接賦值形式只能在構(gòu)造函數(shù) constructor 中使用。

3、setState()函數(shù)
setState()函數(shù)接受兩種形式的對(duì)象。

  • 普通的對(duì)象
    this.setState({comment:"Hello"});
  • 箭頭函數(shù)對(duì)象,箭頭函數(shù)的參數(shù),參數(shù)1是上個(gè)狀態(tài)的 state,參數(shù)2是更新時(shí)的 props 屬性
    this.setState((prevState,props) =>({
        comment:prevState.comment + `{props.name}`
    });
  • 也可以是常規(guī)函數(shù)
    this.setState(function(prevState,props){
        return {comment:prevState.comment + `{props.name}`};
    });

函數(shù)對(duì)象的參數(shù)可選的。

4、state狀態(tài)的變量是合并而不是覆蓋。
就是 setState()函數(shù)只會(huì)設(shè)置對(duì)應(yīng)的變量不影響其他變量。

函數(shù)事件需要綁定的原因分析:
ES6中 function var 聲明的變量是全局變量。

五、條件渲染

布爾值 && 表達(dá)式
布爾值為 false,直接忽略渲染。
布爾值為 true,返回表達(dá)式的渲染。

布爾值 ? 表達(dá)式1 : 表達(dá)式2
布爾值為 true 時(shí),渲染表達(dá)式1
布爾值為 false 時(shí),渲染表達(dá)式2

六、阻止渲染

Booleans, Null, 和 Undefined 被忽略
以下等價(jià):

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

七、屬性擴(kuò)展

如果你已經(jīng)有一個(gè) object 類型的 props,并且希望在 JSX 中傳入,你可以使用擴(kuò)展操作符 ... 傳入整個(gè) props 對(duì)象。這兩個(gè)組件是等效的:

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
  const props = {firstName: 'Ben', lastName: 'Hector'};
  return <Greeting {...props} />;
}

當(dāng)你構(gòu)建一個(gè)一般容器時(shí),屬性擴(kuò)展非常有用。然而,這可能會(huì)使得你的代碼非常混亂,因?yàn)檫@非常容易使一些不相關(guān)的 props(屬性) 傳遞給組件,而組件并不需要這些 props(屬性) 。因此我們建議謹(jǐn)慎使用該語法。

八、通過 PropTypes 進(jìn)行類型檢查

import PropTypes from 'prop-types';

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

// 類型檢查
Greeting.propTypes = {
  name: PropTypes.string
};

// 指定 props 的默認(rèn)值:
Greeting.defaultProps = {
  name: 'Stranger'
};

類型檢查

MyComponent.propTypes = {
  // 你可以聲明一個(gè) prop 是一個(gè)特定的 JS 原始類型。 
  // 默認(rèn)情況下,這些都是可選的。
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

  // 任何東西都可以被渲染:numbers, strings, elements,或者是包含這些類型的數(shù)組(或者是片段)。
  optionalNode: PropTypes.node,

  // 一個(gè) React 元素。
  optionalElement: PropTypes.element,

  // 你也可以聲明一個(gè) prop 是類的一個(gè)實(shí)例。 
  // 使用 JS 的 instanceof 運(yùn)算符。
  optionalMessage: PropTypes.instanceOf(Message),

  // 你可以聲明 prop 是特定的值,類似于枚舉
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),

  // 一個(gè)對(duì)象可以是多種類型其中之一
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // 一個(gè)某種類型的數(shù)組
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // 屬性值為某種類型的對(duì)象
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // 一個(gè)特定形式的對(duì)象
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),

  // 你可以使用 `isRequired' 鏈接上述任何一個(gè),以確保在沒有提供 prop 的情況下顯示警告。
  requiredFunc: PropTypes.func.isRequired,

  // 任何數(shù)據(jù)類型的值
  requiredAny: PropTypes.any.isRequired,

  // 你也可以聲明自定義的驗(yàn)證器。如果驗(yàn)證失敗返回 Error 對(duì)象。不要使用 `console.warn` 或者 throw ,
  // 因?yàn)檫@不會(huì)在 `oneOfType` 類型的驗(yàn)證器中起作用。
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },

  // 也可以聲明`arrayOf`和`objectOf`類型的驗(yàn)證器,如果驗(yàn)證失敗需要返回Error對(duì)象。
  // 會(huì)在數(shù)組或者對(duì)象的每一個(gè)元素上調(diào)用驗(yàn)證器。驗(yàn)證器的前兩個(gè)參數(shù)分別是數(shù)組或者對(duì)象本身,
  // 以及當(dāng)前元素的鍵值。
  customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  })
 }

九、Refs 和 DOM

在 DOM 元素上添加 Ref
React 支持給任何組件添加特殊屬性。ref 屬性接受回調(diào)函數(shù),并且當(dāng)組件 裝載(mounted) 或者 卸載(unmounted) 之后,回調(diào)函數(shù)會(huì)立即執(zhí)行。
當(dāng)給 HTML 元素添加 ref 屬性時(shí), ref 回調(diào)接受底層的 DOM 元素作為參數(shù)。例如,下面的代碼使用ref 回調(diào)來存儲(chǔ) DOM 節(jié)點(diǎn)的引用。

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    // 通過使用原生API,顯式地聚焦text輸入框
    this.textInput.focus();
  }

  render() {
    // 在實(shí)例中通過使用`ref`回調(diào)函數(shù)來存儲(chǔ)text輸入框的DOM元素引用(例如:this.textInput)
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

為 類(Class) 組件添加 Ref

當(dāng) ref 屬性用于類(class)聲明的自定義組件時(shí),ref 回調(diào)函數(shù)收到的參數(shù)是裝載(mounted)的組件實(shí)例。例如,如果我們想包裝 CustomTextInput 組件,實(shí)現(xiàn)組件在 裝載(mounted) 后立即點(diǎn)擊的效果:

class AutoFocusTextInput extends React.Component {
  componentDidMount() {
    this.textInput.focus();
  }

  render() {
    return (
      <CustomTextInput
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

需要注意的是,這種方法僅對(duì)以類(class)聲明的 CustomTextInput 有效:

class CustomTextInput extends React.Component {
  // ...
}

舊版API: String 類型的 Refs
如果你之前使用過 React ,你可能了解過之前的API中的 string 類型的 ref 屬性。類似于 "textInput" ,可以通過 this.refs.textInput 訪問DOM節(jié)點(diǎn)。我們不建議使用,因?yàn)閟tring類型的 refs 存在問題。已經(jīng)過時(shí)了,可能會(huì)在未來的版本是移除。如果你目前還在使用 this.refs.textInput 這種方式訪問 refs ,我們建議用回調(diào)函數(shù)的方式代替。

后面內(nèi)容全部來自談一談創(chuàng)建React Component的幾種方式

1.createClass

如果你還沒有使用ES6語法,那么定義組件,只能使用React.createClass這個(gè)helper來創(chuàng)建組件,下面是一段示例:

var React = require("react");
var Greeting = React.createClass({

  propTypes: {
    name: React.PropTypes.string //屬性校驗(yàn)
  },

  getDefaultProps: function() {
    return {
      name: 'Mary' //默認(rèn)屬性值
    };
  },

  getInitialState: function() {
    return {count: this.props.initialCount}; //初始化state
  },

  handleClick: function() {
    //用戶點(diǎn)擊事件的處理函數(shù)
  },

  render: function() {
    return <h1>Hello, {this.props.name}</h1>;
  }
});
module.exports = Greeting;

這段代碼,包含了組件的幾個(gè)關(guān)鍵組成部分,這種方式下,組件的props、state等都是以對(duì)象屬性的方式組合在一起,其中默認(rèn)屬props和初始state都是返回對(duì)象的函數(shù),propTypes則是個(gè)對(duì)象。這里還有一個(gè)值得注意的事情是,在createClass中,React對(duì)屬性中的所有函數(shù)都進(jìn)行了this綁定,也就是如上面的hanleClick其實(shí)相當(dāng)于handleClick.bind(this)

2.component

因?yàn)镋S6對(duì)類和繼承有語法級(jí)別的支持,所以用ES6創(chuàng)建組件的方式更加優(yōu)雅,下面是示例:

import React from 'react';
class Greeting extends React.Component {

  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
    this.handleClick = this.handleClick.bind(this);
  }

  //static defaultProps = {
  //  name: 'Mary'  //定義defaultprops的另一種方式
  //}

  //static propTypes = {
    //name: React.PropTypes.string
  //}

  handleClick() {
    //點(diǎn)擊事件的處理函數(shù)
  }

  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Greeting.propTypes = {
  name: React.PropTypes.string
};

Greeting.defaultProps = {
  name: 'Mary'
};
export default Greating;

可以看到Greeting繼承自React.component,在構(gòu)造函數(shù)中,通過super()來調(diào)用父類的構(gòu)造函數(shù),同時(shí)我們看到組件的state是通過在構(gòu)造函數(shù)中對(duì)this.state進(jìn)行賦值實(shí)現(xiàn),而組件的props是在類Greeting上創(chuàng)建的屬性,如果你對(duì)類的屬性對(duì)象的屬性的區(qū)別有所了解的話,大概能理解為什么會(huì)這么做。對(duì)于組件來說,組件的props是父組件通過調(diào)用子組件向子組件傳遞的,子組件內(nèi)部不應(yīng)該對(duì)props進(jìn)行修改,它更像是所有子組件實(shí)例共享的狀態(tài),不會(huì)因?yàn)樽咏M件內(nèi)部操作而改變,因此將props定義為類Greeting的屬性更為合理,而在面向?qū)ο蟮恼Z法中類的屬性通常被稱作靜態(tài)(static)屬性,這也是為什么props還可以像上面注釋掉的方式來定義。對(duì)于Greeting類的一個(gè)實(shí)例對(duì)象的state,它是組件對(duì)象內(nèi)部維持的狀態(tài),通過用戶操作會(huì)修改這些狀態(tài),每個(gè)實(shí)例的state也可能不同,彼此間不互相影響,因此通過this.state來設(shè)置。

用這種方式創(chuàng)建組件時(shí),React并沒有對(duì)內(nèi)部的函數(shù),進(jìn)行this綁定,所以如果你想讓函數(shù)在回調(diào)中保持正確的this,就要手動(dòng)對(duì)需要的函數(shù)進(jìn)行this綁定,如上面的handleClick,在構(gòu)造函數(shù)中對(duì)this 進(jìn)行了綁定。

3.PureComponet

我們知道,當(dāng)組件的props或者state發(fā)生變化的時(shí)候:React會(huì)對(duì)組件當(dāng)前的Props和State分別與nextProps和nextState進(jìn)行比較,當(dāng)發(fā)現(xiàn)變化時(shí),就會(huì)對(duì)當(dāng)前組件以及子組件進(jìn)行重新渲染,否則就不渲染。有時(shí)候?yàn)榱吮苊饨M件進(jìn)行不必要的重新渲染,我們通過定義shouldComponentUpdate來優(yōu)化性能。例如如下代碼:

class CounterButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: 1};
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    );
  }
}

shouldComponentUpdate通過判斷props.colorstate.count是否發(fā)生變化來決定需不需要重新渲染組件,當(dāng)然有時(shí)候這種簡單的判斷,顯得有些多余和樣板化,于是React就提供了PureComponent來自動(dòng)幫我們做這件事,這樣就不需要手動(dòng)來寫shouldComponentUpdate了:

class CounterButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {count: 1};
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    );
  }
}

大多數(shù)情況下, 我們使用PureComponent能夠簡化我們的代碼,并且提高性能,但是PureComponent的自動(dòng)為我們添加的shouldComponentUpate函數(shù),只是對(duì)props和state進(jìn)行淺比較(shadow comparison),當(dāng)props或者state本身是嵌套對(duì)象或數(shù)組等時(shí),淺比較并不能得到預(yù)期的結(jié)果,這會(huì)導(dǎo)致實(shí)際的props和state發(fā)生了變化,但組件卻沒有更新的問題,例如下面代碼有一個(gè)ListOfWords組件來將單詞數(shù)組拼接成逗號(hào)分隔的句子,它有一個(gè)父組件WordAdder讓你點(diǎn)擊按鈕為單詞數(shù)組添加單詞,但他并不能正常工作:

class ListOfWords extends React.PureComponent {
  render() {
    return <div>{this.props.words.join(',')}</div>;
  }
 }

class WordAdder extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      words: ['marklar']
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // 這個(gè)地方導(dǎo)致了bug
    const words = this.state.words;
    words.push('marklar');
    this.setState({words: words});
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick} />
        <ListOfWords words={this.state.words} />
      </div>
    );
  }
}

這種情況下,PureComponent只會(huì)對(duì)this.props.words進(jìn)行一次淺比較,雖然數(shù)組里面新增了元素,但是this.props.words與nextProps.words指向的仍是同一個(gè)數(shù)組,因此this.props.words !== nextProps.words 返回的便是flase,從而導(dǎo)致ListOfWords組件沒有重新渲染,筆者之前就因?yàn)閷?duì)此不太了解,而隨意使用PureComponent,導(dǎo)致state發(fā)生變化,而視圖就是不更新,調(diào)了好久找不到原因~。

最簡單避免上述情況的方式,就是避免使用可變對(duì)象作為props和state,取而代之的是每次返回一個(gè)全新的對(duì)象,如下通過concat來返回新的數(shù)組:

handleClick() {
  this.setState(prevState => ({
    words: prevState.words.concat(['marklar'])
  }));
}

你可以考慮使用Immutable.js來創(chuàng)建不可變對(duì)象,通過它來簡化對(duì)象比較,提高性能。
這里還要提到的一點(diǎn)是雖然這里雖然使用了Pure這個(gè)詞,但是PureComponent并不是純的,因?yàn)閷?duì)于純的函數(shù)或組件應(yīng)該是沒有內(nèi)部狀態(tài),對(duì)于stateless component更符合純的定義,不了解純函數(shù)的同學(xué),可以參見這篇文章。

4.Stateless Functional Component

上面我們提到的創(chuàng)建組件的方式,都是用來創(chuàng)建包含狀態(tài)和用戶交互的復(fù)雜組件,當(dāng)組件本身只是用來展示,所有數(shù)據(jù)都是通過props傳入的時(shí)候,我們便可以使用Stateless Functional Component來快速創(chuàng)建組件。例如下面代碼所示:

import React from 'react';
const Button = ({
  day,
  increment
}) => {
  return (
    <div>
      <button onClick={increment}>Today is {day}</button>
    </div>
  )
}

Button.propTypes = {
  day: PropTypes.string.isRequired,
  increment: PropTypes.func.isRequired,
}

這種組件,沒有自身的狀態(tài),相同的props輸入,必然會(huì)獲得完全相同的組件展示。因?yàn)椴恍枰P(guān)心組件的一些生命周期函數(shù)和渲染的鉤子,所以不用繼承自Component顯得更簡潔。

對(duì)比

createClass vs Component

對(duì)于React.createClass

extends React.Component本質(zhì)上都是用來創(chuàng)建組件,他們之間并沒有絕對(duì)的好壞之分,只不過一個(gè)是ES5的語法,一個(gè)是ES6的語法支持,只不過createClass支持定義PureRenderMixin,這種寫法官方已經(jīng)不再推薦,而是建議使用PureComponent。

pureComponent vs Component

通過上面對(duì)PureComponent和Component的介紹,你應(yīng)該已經(jīng)了解了二者的區(qū)別:PureComponent已經(jīng)定義好了shouldUpdateComponentComponent需要顯示定義。

Component vs Stateless Functional component

  1. Component包含內(nèi)部state,而Stateless Functional Component所有數(shù)據(jù)都來自props,沒有內(nèi)部state;

  2. Component

    包含的一些生命周期函數(shù),Stateless Functional Component都沒有,因?yàn)?code>Stateless Functional component沒有shouldComponentUpdate,所以也無法控制組件的渲染,也即是說只要是收到新的props,Stateless Functional Component就會(huì)重新渲染。

  3. Stateless Functional Component

    <a style="box-sizing: border-box; background: transparent; color: rgb(0, 154, 97); text-decoration: none; outline: 0px; border-bottom: 1px solid rgba(0, 154, 97, 0.25); padding-bottom: 1px;">不支持Refs</a>

選哪個(gè)?

這里僅列出一些參考:

  1. createClass, 除非你確實(shí)對(duì)ES6的語法一竅不通,不然的話就不要再使用這種方式定義組件。

  2. Stateless Functional Component, 對(duì)于不需要內(nèi)部狀態(tài),且用不到生命周期函數(shù)的組件,我們可以使用這種方式定義組件,比如展示性的列表組件,可以將列表項(xiàng)定義為Stateless Functional Component。

  3. PureComponent/Component,對(duì)于擁有內(nèi)部state,使用生命周期的函數(shù)的組件,我們可以使用二者之一,但是大部分情況下,我更推薦使用PureComponent,因?yàn)樗峁┝烁玫男阅埽瑫r(shí)強(qiáng)制你使用不可變的對(duì)象,保持良好的編程習(xí)慣。

總結(jié)來自:
React中文
談一談創(chuàng)建React Component的幾種方式

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容