简体   繁体   English

React-使用onClick事件更改材质图标

[英]React - Change Material Icon With onClick Event

I'm trying to change the material icon from add to remove with an on click event in React. 我正在尝试在React中通过单击事件将材质图标从添加更改为删除 To clear up some confusion, this has nothing to do with classes, it's to do with the material icon that actually displays. 为了消除混乱,这与类无关,与实际显示的材质图标有关。 Add is a plus icon, I need to change it from add to remove, which is a subtract icon. 添加是加号图标,我需要将其从添加更改为删除,这是一个减号图标。

handleClick() {
    console.log('test');    
}

render() {
    <div>
        <i className="material-icons mobile" onClick={(e) => this.handleClick(e)}>add</i>
    </div> 
}

The above works console outputs test perfectly fine, I just have no idea how to approach this. 上面的工作控制台输出测试完全正常,我只是不知道该如何处理。 Done some research online and can't find anything about this. 在网上做了一些研究,却找不到任何相关信息。 Could use with some insight or ideas for an approach to this. 可以结合一些见解或想法来使用此方法。

You can do that by setting state. 您可以通过设置状态来做到这一点。 Something like this: 像这样:

state = { icon: true }

handleClick = e => {
    const { icon } = this.state
    this.setState({ icon: !icon })   
}

render() {
    const { icon } = this.state
    return(
        <i className='large material-icons' onClick={this.handleClick}>
            { icon ? 'add' : 'remove'}
        </i>
    )

}

Improving the last answer: 改善最后的答案:

constructor() {
    super();
    this.state = { icon: true };
}

handleClick() {
    this.setState({ icon: !this.state.icon })   
}

render() {
    <i className='large material-icons' onClick={(e) => this.handleClick(e)}>
        { this.state.icon ? 'add' : 'remove' }
    </i>
}

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

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