2016-05-13 93 views
-1

我正在使用组件的ES6类在Reactjs中制作应用程序。 代码按预期工作,直到我想用参数调用类中的函数。如何使用ES6类中的参数调用函数?

SampleClass.js

class SampleClass extends React.Component { 
    constructor(props, context) { 
     super(props, context); 
     this.state = { 
     backgroundColor: 'yellow' 
     } 
    } 

    onChangeBackgroundColor(backgroundColor) { 
     this.setState({ 
     backgroundColor: backgroundColor 
     }) 
    } 

    render() { 
     return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}> 
     <span onClick={this.onChangeBackgroundColor.bind(this)} style={{background: 'white'}}> 
      Change element style 
     </span> 
     </div> 
    } 
} 

React.render(<SampleClass />, document.getElementById('container')); 

我能够调用一个函数罚款不带参数一样this.onChangeBackgroundColor.bind(this)

但是,当我尝试向该函数传递参数时,控制台中出现错误 Uncaught TypeError: Cannot read property 'bind' of undefined

参考小提琴:https://jsfiddle.net/purezen/s6ap3m8s/3/

+0

请您分享一个例子,您包括参数? –

回答

2
this.onChangeBackgroundColor.bind(this, arg1, arg2) 

你的论据应该在绑定呼叫,this后,如果你希望他们被绑定到的功能。

由于@ivarni陈述和每个阵营的文档最好是在构造函数中进行绑定,请参阅以下链接了解更多信息

“我们建议您绑定你的事件处理程序的构造函数,因此他们只绑定一次,每一个实例:”

https://facebook.github.io/react/docs/reusable-components.html

+1

你应该在'构造函数'中绑定函数。将它们绑定到'render'意味着它们必须在组件每次渲染而不是仅仅执行一次时进行绑定。 – ivarni

+0

你是对的,我会将其添加到我的答案中。 – sheeldotme

0

我编辑你的小提琴,路过red值,和它的作品。

你可以看到它here

您需要的参数传递给bind功能

0

一种更好的方式来处理点击结合纠正传递的参数的这个值是使用ES6 lambda表达式() =>因为他们从词汇上绑定这个正确的值:

render() { 
    return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}> 
    <span onClick={() => this.onChangeBackgroundColor(arg1, arg2)} style={{background: 'white'}}> 
     Change element style 
    </span> 
    </div> 
} 
相关问题