我正在使用組件的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/
請您分享一個例子,您包括參數? –