gpt4 book ai didi

javascript - react 切换按钮问题

转载 作者:行者123 更新时间:2023-11-29 21:15:47 33 4
gpt4 key购买 nike

我正在尝试获得此开关 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>
)
}
};

有没有人知道我在事件中获取 undefined 做错了什么,以及关于如何为我可以在 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com