2016-05-13 91 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> 
} 
相關問題