react方法传参的两种方式

Posted on 2019-07-08 21:30  猫头唔食鱼  阅读(4321)  评论(0编辑  收藏  举报

1.使用bind

import React, { Component } from 'react'
class App extends Component{
  constructor(props){
    super(props)
    this.state = {
      test:"哈哈"
    }
  }
  render(){
    return(
      <div>
        <button onClick={this.getValue.bind(this,this.state.test)}>确定</button>
      </div>
    )
  }
  getValue(val){
    console.log(val);
  }
}
export default App ;

 

2.使用箭头函数

import React, { Component } from 'react'
class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      test: "哈哈"
    }
  }
  render() {
    return (
      <div>
        <button onClick={() => this.getVal(this.state.test)}>确定</button>
      </div>
    )
  }

  getVal = (val) => {
    console.log(val);
  }
}
export default App;