react實現(xiàn)數(shù)據(jù)監(jiān)聽方式
react 數(shù)據(jù)監(jiān)聽
監(jiān)聽組件傳遞的值:
?componentWillReceiveProps(newProps)
?{
??? ?參數(shù)為給組件傳遞的參數(shù)
?}監(jiān)聽組件內(nèi)部狀態(tài)的變化:
componentDidUpdate(prevProps,prevState){
?? ?參數(shù)分別為改變之前的數(shù)據(jù)狀態(tài)對象
?? ?if(prevState.屬性名!=this.state.屬性名)
?? ?{
?? ??? ?...
?? ?}
}react事件監(jiān)聽三種寫法
方式一
在constructor中使用bind綁定,改變this的指向
import React, { Component } from 'react';
?
export default class Group extends Component {
? constructor(props) {
? ? super(props);
? ? this.state = {
? ? ? show: true,
? ? ? title: '大西瓜'
? ? };
? ? // 寫法一:事件綁定改變this指向
? ? this.showFunc = this.showFunc.bind(this);
? }
? // 調(diào)用該方法
? showFunc() {
? ? this.setState({
? ? ? show: false
? ? });
? }
? render() {
? ? let result = this.state.show ? this.state.title : null;
? ? return (
? ? ? <div>
? ? ? ? <button onClick={this.showFunc}>觸發(fā)</button>
? ? ? ? {result}
? ? ? </div>
? ? );
? }
}方式二
通過箭頭函數(shù)改變this指向
import React, { Component } from 'react';
?
export default class Group extends Component {
? constructor(props) {
? ? super(props);
? ? this.state = {
? ? ? show: true,
? ? ? title: '大西瓜'
? ? };
? }
? // 第二種,通過箭頭函數(shù)改變this指向
? showFunc = () => {
? ? this.setState({
? ? ? show: false
? ? });
? };
? render() {
? ? let result = this.state.show ? this.state.title : null;
? ? return (
? ? ? <div>
? ? ? ? <button onClick={this.showFunc}>觸發(fā)</button>
? ? ? ? {result}
? ? ? </div>
? ? );
? }
}方式三
直接使用箭頭函數(shù)改變this的指向
import React, { Component } from 'react';
?
export default class Group extends Component {
? constructor(props) {
? ? super(props);
? ? this.state = {
? ? ? show: true,
? ? ? title: '大西瓜'
? ? };
? }
? // 調(diào)用該方法
? showFunc() {
? ? this.setState({
? ? ? show: false
? ? });
? }
? render() {
? ? let result = this.state.show ? this.state.title : null;
? ? return (
? ? ? <div>
? ? ? ? <button onClick={() => this.showFunc()}>觸發(fā)</button>
? ? ? ? {result}
? ? ? </div>
? ? );
? }
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
React通過redux-persist持久化數(shù)據(jù)存儲的方法示例
這篇文章主要介紹了React通過redux-persist持久化數(shù)據(jù)存儲的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
react中history(push,go,replace)切換路由方法的區(qū)別及說明
這篇文章主要介紹了react中history(push,go,replace)切換路由方法的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
React服務(wù)端渲染和同構(gòu)的實現(xiàn)
本文主要介紹了React服務(wù)端渲染和同構(gòu)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
使用react+redux實現(xiàn)計數(shù)器功能及遇到問題
使用redux管理數(shù)據(jù),由于Store獨立于組件,使得數(shù)據(jù)管理獨立于組件,解決了組件之間傳遞數(shù)據(jù)困難的問題,非常好用,今天重點給大家介紹使用react+redux實現(xiàn)計數(shù)器功能及遇到問題,感興趣的朋友參考下吧2021-06-06
淺談React Native Flexbox布局(小結(jié))
這篇文章主要介紹了淺談React Native Flexbox布局(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
React 如何使用時間戳計算得到開始和結(jié)束時間戳
這篇文章主要介紹了React 如何拿時間戳計算得到開始和結(jié)束時間戳,本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09

