[标准]this传参的几种方式

zhuanbike 2022-1-2 779

    // react事件处理  react绑定事件使用的是小驼峰命名法  在绑定函数的时候不能加() --->函数会立即执行
            // 1.修改this指向
            // 1.bing方式原地绑定
            // 2.函数通过箭头函数进行创建
            // 3.consternation中提前绑定
            // 4吧事件的调用写成箭头函数的调用方式
        class Com extends React.Component{
            constructor(props){
                super(props)
                this.func=this.func.bind(this)
            }
            funa(){
                console.log(this)
            }
            funb=()=>{
                console.log(this)
            }
            func(){
                console.log(this)
            }
            fund(){
                console.log(this)
            }
            fune=(i,e)=>{
                console.log(i)
                console.log(e)
            }
            render(){
                return(
                    <div>
                        我是组件
                        <button onClick={this.funa.bind(this)}>bing方式绑定</button>
                        <button onClick={this.funb}>箭头函数绑定</button>
                        <button onClick={this.func}>提前绑定</button>
                        <button onClick={()=>{this.fund()}}>调用方式为箭头函数</button>
                        <h1>函数实参传递</h1>
                        <button onClick={this.fune.bind(this,"我是参数")}>点我传递实参</button>
                        <button onClick={(e)=>{this.fune("我是参数2",e)}}>点我传递实参2</button>
                    </div>
                )
            }
        }
            ReactDOM.render(<Com />,document.getElementById("demoReact"));

      

         


最新回复 (1)
  • zhuanbike 2022-1-2
    0 引用 2
    箭头函数最为简洁,其他也应了解
发新帖