【问题标题】:React toggle button issue反应切换按钮问题
【发布时间】:2016-09-13 02:51:04
【问题描述】:

我试图让这个开关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 如果有帮助的话

谢谢!

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

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

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

    【讨论】:

    • 我正在动态创建它们,以便完美运行,不敢相信它像第二个 arg 一样简单:D,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2021-09-16
    • 2013-01-18
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多