網站首頁 編程語言 正文
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
相關推薦
- 2022-10-16 C#自定義畫刷原理解析_C#教程
- 2023-05-23 Django?事務回滾的具體實現_python
- 2022-12-30 React代碼分割的實現方法介紹_React
- 2024-07-15 redis中存儲list<map>,list<entity>結構數據如何處理
- 2022-08-17 go?Cobra命令行工具入門教程_Golang
- 2023-08-28 React安裝ant design組件庫,并使用
- 2022-07-16 Linux Redis-6.2.6單機部署
- 2022-11-05 ASP.NET?MVC實現樹形導航菜單_實用技巧
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支