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

學無先后,達者為師

網站首頁 編程語言 正文

react實現數據監聽方式_React

作者:神奇大叔 ? 更新時間: 2022-10-03 編程語言

react 數據監聽

監聽組件傳遞的值:

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

?監聽組件內部狀態的變化:

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

react事件監聽三種寫法

方式一

在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);
? }
? // 調用該方法
? showFunc() {
? ? this.setState({
? ? ? show: false
? ? });
? }
? render() {
? ? let result = this.state.show ? this.state.title : null;
? ? return (
? ? ? <div>
? ? ? ? <button onClick={this.showFunc}>觸發</button>
? ? ? ? {result}
? ? ? </div>
? ? );
? }
}

方式二

通過箭頭函數改變this指向

import React, { Component } from 'react';
?
export default class Group extends Component {
? constructor(props) {
? ? super(props);
? ? this.state = {
? ? ? show: true,
? ? ? title: '大西瓜'
? ? };
? }
? // 第二種,通過箭頭函數改變this指向
? showFunc = () => {
? ? this.setState({
? ? ? show: false
? ? });
? };
? render() {
? ? let result = this.state.show ? this.state.title : null;
? ? return (
? ? ? <div>
? ? ? ? <button onClick={this.showFunc}>觸發</button>
? ? ? ? {result}
? ? ? </div>
? ? );
? }
}

方式三

直接使用箭頭函數改變this的指向

import React, { Component } from 'react';
?
export default class Group extends Component {
? constructor(props) {
? ? super(props);
? ? this.state = {
? ? ? show: true,
? ? ? title: '大西瓜'
? ? };
? }
? // 調用該方法
? showFunc() {
? ? this.setState({
? ? ? show: false
? ? });
? }
? render() {
? ? let result = this.state.show ? this.state.title : null;
? ? return (
? ? ? <div>
? ? ? ? <button onClick={() => this.showFunc()}>觸發</button>
? ? ? ? {result}
? ? ? </div>
? ? );
? }
}

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

欄目分類
最近更新