简体   繁体   English

反应切换按钮问题

[英]React toggle button issue

I'm trying to get this switch https://github.com/pgrimard/react-toggle-switch working in my react project.我试图让这个开关https://github.com/pgrimard/react-toggle-switch在我的反应项目中工作。 It is currently working as expected (it toggles and calls the toggleFeature function), however i'm struggling to understand how I would actually link each switch to perform a different action.它目前按预期工作(它切换并调用 toggleFeature 函数),但是我很难理解我实际上如何链接每个开关以执行不同的操作。 Normally I would just grab some sort of identifiable attribute in the onClick event to determine which action to carry out, But i'm a bit stuck on how to do it in this case.通常我只会在 onClick 事件中获取某种可识别的属性来确定要执行的操作,但在这种情况下我有点不知道如何去做。

Heres my current code (Made it as bare-bones as possible)继承人我目前的代码(尽可能简单)

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>
    )
  }
};

Does any one have any idea what i'm doing wrong to get undefined on the event, Aswell as perhaps some idea's on how I can provide my own unique identifier to each button which I could read in the onClick event?有没有人知道我在事件中未定义的错误,以及关于如何为我可以在 onClick 事件中读取的每个按钮提供我自己的唯一标识符的一些想法?

Heres examples of the button: https://github.com/pgrimard/react-toggle-switch/blob/master/example/app/scripts/main.js#L12 if it's any help这里是按钮的例子: https : //github.com/pgrimard/react-toggle-switch/blob/master/example/app/scripts/main.js#L12如果有帮助的话

Thanks!谢谢!

While binding the _toggleFeature function, you can give it arguments with which it will be called:在绑定_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}/>

Now you can differentiate between the toggles in the handler:现在您可以区分处理程序中的切换:

_toggleFeature(toggleName) {
  if (toggleName === 'toggle1') {
    // Do some logic for toggle 1
  } else if (toggleName === 'toggle2') {
    // Do some logic for toggle 2
  }
}

Alternatively you can have different handler functions for each toggle, unless you are dynamically creating a variable number of switches.或者,您可以为每个切换设置不同的处理函数,除非您动态创建可变数量的开关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM