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)
      } */
    }
    右侧打赏一下 代码改变世界一块二块也是爱
  • 相关阅读:
    第五章总结
    第二章总结
    第一章、基础知识总结
    实验 9 根据材料编程
    实验5
    汇编实验4
    实验 3 编程、编译、连接、跟踪
    实验 2 用机器指令和汇编指令编程
    汇编-实验一
    react面试笔录
  • 原文地址:https://www.cnblogs.com/ht955/p/14667242.html
Copyright © 2011-2022 走看看