我正在使用 React 组件和 es6。 我应该如何将 onChange 方法中的逻辑使用到其他方法中?
render() {
let input;
return (
<tr> <input
ref = {node => { input = node; }}
onChange = { event => {
if (input.value === this.props.word.pl)
event.currentTarget.style.backgroundColor = 'Chartreuse';
else if (input.value !== this.props.word.pl)
event.currentTarget.style.backgroundColor = 'LightCoral';
else if (input.value === "")
event.currentTarget.style.backgroundColor = 'none';
}
}/>
最佳答案
将函数移出组件级别
在构造函数中绑定(bind) this
在多个 onChange 事件上使用它
class MyComponent extends React.Component {
constructor(props) {
super(props);
// bind this
this.handleChange = this.handleChange.bind(this);
}
// reusable function
handleChange(e) {
// ... your logic for onChange here
}
render() {
return (
<div>
<input onChange={this.handleChange} />
<input onChange={this.handleChange} />
</div>
);
}
};
了解有关 React 表单的更多信息 here .
关于javascript - es6 类和 React 组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41034959/