React中JSX回调函数调用与this绑定机制解析

作者:远帆

时间:2026-10-26

浏览:306

本文深入解析React中JSX插值表达式与事件回调函数的调用差异。重点阐述为何直接调用函数需加括号,而事件监听器传递函数引用时不加括号,以及由此引发的this指向丢失问题。通过对比constructor绑定、bind方法及箭头函数等方案,提供清晰的实践指南。

文章目录

探讨函数调用()与bind this的原因

内容主要围绕onClick回调函数的解决方案展开

参考官方文档对jsx回调函数的解释

  • 针对JSX回调函数中的this,JavaScript中class方法默认不绑定this
  • 若忘记绑定this.handleClick并传入onClick,调用时this为undefined
//函数组件则就是 无状态组件  只负责数据的展示(静态)
//类组件这就是有状态组件      负责更新ui,让页面动起来
//状态(state )就是数据,是组件内部的私有数据,只能在组件内部使用
//state的值是对象,即就是一个组件内部可以拥有多个数据
class StateComponent extends React.Component{
  //使用es6简化办法初始化
  //state={
  //  count:0
  //}
   constructor(props) {
    super(props);
    this.state = {count: 0};
    this.addClick3 = this.addClick3.bind(this);
  }
  addClick(){
    this.setState({count : this.state.count + 1});
  }
  addClick2=()=>{
    this.setState({count : this.state.count + 1});
  }
  addClick3(){
    this.setState({count : this.state.count + 1});
  }
  render(){
    return(
      <>
    <button onClick={()=>{
      this.setState({
        count: this.state.count+1
      })
    }}>有状态组件,{this.state.count}</button>

    <button onClick={this.addClick.bind(this)} >不使用constructor,使用注释的es6简化写法</button>
    <button onClick={()=>this.addClick()} >箭头函数使用</button>
    <button onClick={this.addClick2} >使用箭头函数</button>
    <button onClick={this.addClick3} >constructor中进行绑定后可使用</button>
    </>
    )
  }
}

因初学js及react框架,对jsx插值表达式中的函数调用存在疑问

function check(){
}

1、部分插值表达式调用函数无需(),如{check};部分需(),如{check()}

2、React中onClick调用函数,若内部未用this可直接调用{check};若用了this需特殊处理

解答1

界面直接使用jsx插值表达式,若希望直接返回函数结果需用{check()};若等待触发条件再调用则用{check}。()即函数调用,函数名指向函数体指针

react官网对以下问题的解答清晰展示了()的区别

为何我的函数每次组件渲染时都被调用?

确保传递函数给组件时,未调用该函数:

hadleClick(){
 return <div>hello world</div>
 //函数体内部没有使用this
}
render() {
  // Wrong: handleClick is called instead of passed as a reference!
  return <button onClick={this.handleClick()}>Click Me</button>
}

正确做法是传递函数本身(不带括号):

render() {
  // Correct: handleClick is passed as a reference!
  return <button onClick={this.handleClick}>Click Me</button>
}

解答2

js特性:直接调用函数,即使内部用了this也可正常使用;但若非直接调用且内部用了this,则this丢失变为undefined

故代码中renderList()直接调用,使用{this.renderList()},即使内部用了this也无需特殊处理

但onClick并非直接调用,它相当于中间量

函数体内部的this指向会丢失

class Comment extends React.Component{
    state={
         comments:[
            {id:1,name:'jack',comment:"沙发"},
            {id:2,name:"tom",comment:'沙发不错'},
            {id:3,name:"blue",comment:"还行"}
         ]
    }
    renderList(){
        return(
            this.state.comments.kength===0?
                <div className="no-comment" >暂无评论,快去评论</div>:
                <ul >
              {this.state.comments&&this.state.comments.map(comment=>
                  <li key={comment.id}><h3>评论人:{comment.name}</h3>
                  <p>评论内容 :{comment.content}</p>
                  </li>
              )} 
               </ul>
              
        )
    }
      render(){
        return(
            <>
            {this.renderList()}
             </>
        )
      }

}

this丢失可用箭头函数解决,因箭头函数具备如下特质:

使用箭头函数时,默认绑定外层this值,故箭头函数中this与外层this一致

因此可通过箭头函数避免this丢失,当然还有其他多种方式

1、使用es5语法,在初始化component时使用constructor对函数进行绑定

2、在中间量声明时使用bind(this)进行绑定

3、中间量声明函数时使用箭头函数,可直接进行函数调用;或将函数内容直接书写在箭头函数内(注意这里进行函数调用时需要使用函数名+(),因为在函数内部声明是直接调用)

4、最常用方式,使用箭头函数声明函数,则可直接调用,不需要额外处理

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章