簡體   English   中英

ReactJs 如何更改單擊事件上按鈕的圖標?

[英]ReactJs How to change an icon of a button on the click event?

我正在使用material-ui 中IconButton ,我想在單擊/觸摸事件后更改按鈕的圖標。

var tableModeElement =
<IconButton key="tableModeButton" 
 onTouchTap={() => { 
   this.setState(prevState => (
    { isCardView: !prevState.isCardView })) } }>
  <i className="material-icons theme-color-p1">
   {this.state.isCardView ? "view_module" : "list"}
  </i>
</IconButton>

表達式{this.state.isCardView ? "view_module" : "list"} {this.state.isCardView ? "view_module" : "list"}僅評估一次,之后不再評估。 我想如果我改變狀態我會強制重新渲染嗎? 我究竟做錯了什么?

編輯:補充說 iconButton 被分配給一個變量。 如果我將<IconButton>直接包含在渲染方法中,它工作正常。 我不得不重新分配變量以使其工作。

<i>元素中設置文本“view_module”或“list”不會改變按鈕的圖標

您需要在按鈕內有一個嵌套的圖標,例如:

<IconButton key="tableModeButton" 
 onTouchTap={() => { 
   this.setState({
     isCardView: !this.state.isCardView
   })
  }}>
   {this.state.isCardView ? <IconA /> : <IconB /> }
</IconButton>

我相信這會奏效:

class IconButton extends React.Component { 
  constructor(props) {
    super(props);
    this.state = {
      isCardView: false,
    }
  } 

  render() {
    return (
      <a className="btn btn-primary" onClick={()=>this.setState({ isCardView: !this.state.isCardView })}>
        { this.state.isCardView
          ? <span className="glyphicon glyphicon-remove-sign" />
          : <span className="glyphicon glyphicon-ok-sign" />
        }
        &nbsp;&nbsp;BUTTON
      </a>
    );
  }

}

class App extends React.Component { 
  render () {                                        
    return (
      <div>
        <IconButton />  
      </div>
    );
  }
}

ReactDOM.render(<App/>,document.getElementById('root'));

我正在使用引導程序,但任何圖標系統都可以使用

http://codepen.io/cjke/pen/MJvXNo?editors=0010

這是我能想到的最好的方法:

     <IconButton key="tableModeButton" onTouchTap={(e) => { 

        let show = this.state.prevState.isCardView;
        let index = show.indexOf('show');

        if (index != -1) {
           show = 'hide';
        } else {
           show = 'show';
        }

        this.setState(prevState => ({ isCardView: show }));
        event.preventDefault()

} }>

<IconButton>使用的圖標由它的 iconClassName 屬性定義。

之后它可能看起來像這樣。

<IconButton key="tableModeButton" 
  onTouchTap={() => { 
     this.setState( prevState => {isCardView: !prevState.isCardView} ) }
  }
  iconClassName={this.state.isCardView ? "view_module" : "list"} />
</IconButton>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM