zoukankan      html  css  js  c++  java
  • React中方法的this绑定

    第一种 在组件(类)的constructor中绑定this

     1 class Demo extends Component {
     2   constructor(this) {
     3     super(this)
     4     this.state = { value: 0 }
     5     this.handleDivClick = this.handleDivClick.bind(this)
     6   }
     7 
     8   handleDivClick() {
     9     this.setState((state, props) => ({ value: state.value + 1 }))
    10   }
    11 
    12   render() {
    13     const { value } = this.state
    14     return <div onClick={this.handleDivClick}>{value}</div>
    15   }
    16 }

    第二种 使用 public class fields 语法(实验性质)

     1 class Demo extends Component {
     2   ...
     3 
     4   handleClick = () => {
     5     console.log('"this" is: ', this)
     6   }
     7 
     8   render() {
     9     return <button onClick={this.handleClick}>Get log</button>
    10   }
    11 }

     关于类字段语法(参考Babel官网):

     1 class Book {
     2   // Property initializer syntax (属性初始化器语法)
     3   instanceProperty = 'book'
     4   boundFunction = () => {
     5     return this.instanceProperty
     6   }
     7 
     8   // Static class properties (静态属性)
     9   static staticProperty = 'pencil'
    10   static staticFunction = function() {
    11     return Bork.staticProperty
    12   }
    13 }
    14 
    15 let myBork = new Bork
    16 
    17 // Property initializers are not on the prototype.
    18 console.log(myBork.__proto__.boundFunction) // undefined
    19 
    20 // Bound functions are bound to the class instance.
    21 console.log(myBork.boundFunction.call(undefined)) // 'bork'
    22 
    23 // Static function exists on the class. 
    24 console.log(Bork.staticFunction()) // 'pencil'

    第三种 使用箭头函数

     1 class Demo extends Component {
     2   ...
     3 
     4   handleClick() {
     5     // ...
     6   }
     7 
     8   render() {
     9     return (
    10       <button onClick={e => this.handleClick(e)}>Click me</button>
    11     )
    12   }
    13 }

    绑定事件的传参

    1 // 1.
    2 <button onClick={e => this.handleClick(e, id)}>Click</button>
    3 
    4 // 2. 
    5 <button onClick={this.handleClick.bind(this, id)}>Click</button>
  • 相关阅读:
    1、远程连接工具
    Restful架构API编码规范
    61、springmvc-异步请求-返回DeferredResult
    60、springmvc-异步请求-返回Callable
    59、servlet3.0-异步请求
    58、springmvc-定制与接管SpringMVC
    HTTP层 —— 响应
    HTTP层 —— 请求
    HTTP层 —— 控制器
    HTTP层 —— CSRF保护
  • 原文地址:https://www.cnblogs.com/fanqshun/p/10041241.html
Copyright © 2011-2022 走看看