繁体   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