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)
      } */
    }
    右侧打赏一下 代码改变世界一块二块也是爱
  • 相关阅读:
    AFN 控制字符报错(无法解析)
    HTTP POST请求报文格式分析与Java实现文件上传
    xcrun
    Makefile选项CFLAGS,LDFLAGS,LIBS
    Xcode 编译错误
    iOS 11 适配
    机器学习算法之决策树
    Python extend 和 append 的区别
    Python warning_function name should be lowercase
    使用matplotlib绘制导数图像
  • 原文地址:https://www.cnblogs.com/ht955/p/14667242.html
Copyright © 2011-2022 走看看