zoukankan      html  css  js  c++  java
  • react this指向问题

    在JSX事件函数方法中的 this,默认不会绑定 this指向。如果你忘记绑定,当你调用这个函数的时候 this 的值为 undefined。所以使用时一定要绑定好this的指向。

    • 构造方法中绑定

    constructor(props){

        super(props)

        // 在构造方法中指定this指向  <button onClick={this.fun()}>按钮</button>

        this.fun = this.fun.bind(this)

    }

    import React, { Component } from 'react'
    
    export default class Userthis extends Component {
    
      // 方案解决this指向问题
      constructor(props) {
        super(props);
        // 手动绑定this的指向
        // this.fn = this.fn.bind(this)
      }
    
    
    
      render() {
        return (
          <div>
            {/* <button onClick={this.fn}>获取父组传过来的数据</button> */}
    
            {/* 方案2 在绑定方法中使用bind */}
            {/* <button onClick={this.fn.bind(this)}>获取父组传过来的数据</button> */}
    
            {/* 方案3 箭头函数绑定 */}
            {/* <button onClick={() => this.fn()}>获取父组传过来的数据</button> */}
    
            {/* 方案4 在绑定实现的方法中定义使用箭头函数 */}
            <button onClick={this.fn}>获取父组传过来的数据</button>
    
          </div>
        )
      }
      // 方案4
      fn = () => {
        console.log(this.props)
      }
    
      
      /* fn() {
        console.log(this.props)
      } */
    }
    右侧打赏一下 代码改变世界一块二块也是爱
  • 相关阅读:
    国内10大前端团队网站
    可视化搭建前端工程
    Vue CLI环境变量和模式
    BetterScroll:可能是目前最好用的移动端滚动插件
    洛谷月赛
    CF438D The Child and Sequence
    P1447 [NOI2010]能量采集
    Cow Relays,过N条边的最短路
    Numerical Sequence(hard version),两次二分
    洛谷P3237 米特运输
  • 原文地址:https://www.cnblogs.com/ht955/p/14667242.html
Copyright © 2011-2022 走看看