簡體   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