繁体   English   中英

反应切换按钮问题

[英]React toggle button issue

我试图让这个开关https://github.com/pgrimard/react-toggle-switch在我的反应项目中工作。 它目前按预期工作(它切换并调用 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如果有帮助的话

谢谢!

在绑定_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
  }
}

或者,您可以为每个切换设置不同的处理函数,除非您动态创建可变数量的开关。

暂无
暂无

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

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