日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

react實(shí)現(xiàn)數(shù)據(jù)監(jiān)聽(tīng)方式_React

作者:神奇大叔 ? 更新時(shí)間: 2022-10-03 編程語(yǔ)言

react 數(shù)據(jù)監(jiān)聽(tīng)

監(jiān)聽(tīng)組件傳遞的值:

?componentWillReceiveProps(newProps)
?{
??? ?參數(shù)為給組件傳遞的參數(shù)
?}

?監(jiān)聽(tīng)組件內(nèi)部狀態(tài)的變化:

componentDidUpdate(prevProps,prevState){
?? ?參數(shù)分別為改變之前的數(shù)據(jù)狀態(tài)對(duì)象
?? ?if(prevState.屬性名!=this.state.屬性名)
?? ?{
?? ??? ?...
?? ?}
}

react事件監(jiān)聽(tīng)三種寫法

方式一

在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>
? ? );
? }
}

方式二

通過(guò)箭頭函數(shù)改變this指向

import React, { Component } from 'react';
?
export default class Group extends Component {
? constructor(props) {
? ? super(props);
? ? this.state = {
? ? ? show: true,
? ? ? title: '大西瓜'
? ? };
? }
? // 第二種,通過(guò)箭頭函數(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>
? ? );
? }
}

原文鏈接:https://blog.csdn.net/weixin_43294560/article/details/106583597

欄目分類
最近更新