千家信息网

React事件监听的代码怎么写

发表于:2024-10-25 作者:千家信息网编辑
千家信息网最后更新 2024年10月25日,这篇文章主要介绍"React事件监听的代码怎么写"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"React事件监听的代码怎么写"文章能帮助大家解决问题。方法一:
千家信息网最后更新 2024年10月25日React事件监听的代码怎么写

这篇文章主要介绍"React事件监听的代码怎么写"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"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 (      
{result}
); }}

方法二:通过箭头函数改变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 (      
{result}
); }}

方法三:直接使用箭头函数改变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 (      
{result}
); }}

关于"React事件监听的代码怎么写"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注行业资讯频道,小编每天都会为大家更新不同的知识点。

0