react组件成员函数绑定写法

用ES6书写react组件成员函数绑定的三种方法如下,推荐使用第三种

第一种,使用bind来绑定

//创建组件
class myComponent extends React.Component{
    constructor(props){
        super(props);
        this.state={
        }
    }
//内部成员函数
    handleClick(){
        console.log('我被点击了')
    }
    render(){
        return(
            
) } }

第二种,在构造函数中绑定

//创建组件
class myComponent extends React.Component{
    constructor(props){
        super(props);
        this.state={
        }
        this.handleClick=this.handleClick.bind(this)
    }
//内部成员函数
    handleClick(){
        console.log('我被点击了')
    }
    render(){
        return(
            
) } }

第三种,使用箭头函数

//创建组件
class myComponent extends React.Component{
    constructor(props){
        super(props);
        this.state={
        }
    }
//内部成员函数
    handleClick(){
        console.log('我被点击了')
    }
    render(){
        return(
            
this.handleClick()}>
) } }

你可能感兴趣的:(react组件成员函数绑定写法)