我正在尝试获取此开关 https://github.com/pgrimard/react-toggle-switch在我的 react 项目中工作。它目前正在按预期工作(它切换并调用toggleFeature函数),但是我正在努力理解如何实际链接每个开关以执行不同的操作。通常我会在 onClick 事件中获取某种可识别的属性来确定要执行哪个操作,但在这种情况下我对如何执行此操作有点困惑。
这是我当前的代码(尽可能简单)
class FeatureItem extends React.Component {
constructor(props) {
super(props);
this.state = {on: props.flag};
}
_toggleFeature(e) {
console.log(e); // Undefined
console.log("ASSD"); // Called on the toggle
}
render () {
<div className="example-usage">
<p>Switch state: {this.state.on ? 'On' : 'Off'}</p>
<Switch className= {this.props.description} onClick={this._toggleFeature.bind(this)} on={this.state.on}/>
</div>
)
}
};
有谁知道我做错了什么而导致事件未定义,以及也许有一些想法关于如何为每个按钮提供我自己的唯一标识符,以便我可以在 onClick 事件中读取?
以下是该按钮的示例:https://github.com/pgrimard/react-toggle-switch/blob/master/example/app/scripts/main.js#L12如果有帮助的话
谢谢!
最佳答案
绑定(bind) _toggleFeature
函数时,您可以为其提供调用它的参数:
<Switch className= {this.props.description} onClick={this._toggleFeature.bind(this, 'toggle1')} on={this.state.on1}/>
<Switch className= {this.props.description} onClick={this._toggleFeature.bind(this, 'toggle2')} on={this.state.on2}/>
现在您可以区分处理程序中的切换:
_toggleFeature(toggleName) {
if (toggleName === 'toggle1') {
// Do some logic for toggle 1
} else if (toggleName === 'toggle2') {
// Do some logic for toggle 2
}
}
或者,您可以为每个切换设置不同的处理函数,除非您动态创建可变数量的开关。
关于javascript - React 切换按钮问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39456760/