ReactJs如何在点击事件中更改按钮的图标?

4

我正在使用material-uiIconButton,并且我想在单击/触摸事件后更改按钮的图标。

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"} 只被计算一次,之后不再计算。我原以为如果我改变state,就可以强制重新渲染,那我做错了什么呢?
编辑:添加了IconButton被分配给一个变量的信息。如果将<IconButton>直接包含在render方法中,它就可以正常工作。我必须重新分配变量才能使它正常工作。

也许如果您告诉我们您使用的图标集以及您想要如何集成它,那么这可能会有所帮助。 - skAstro
4个回答

4
我相信这个方案可行:
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'));

我正在使用Bootstrap,但任何图标系统都可以使用。 http://codepen.io/cjke/pen/MJvXNo?editors=0010

这可能可以正常工作。我的结构中有一些逻辑错误。由于它存储在变量中,我需要通过手动调用来强制重新渲染。 - Murat Karagöz
出于好奇,您为什么要将它存储在变量中?99%的情况下,只需进行一点清理就不需要强制重新渲染。 - Chris
它是一个更大UI的一部分,为了保持模块化。这个按钮基本上属于标题。 - Murat Karagöz
啊,好的 - 所以“isCardView”实际上是标题的状态,而不是单独的按钮? - Chris

2

<i>元素中设置文本“view_module”或“list”将不会更改按钮的图标。

您需要在按钮内嵌套一个图标,例如:

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

尝试使用我刚编辑的不同的“set state”调用。 - Marty

1
这是我能想到的最好方案:
     <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()

} }>

这并不是我正在寻找的。我不想隐藏它,更像是翻转图标。 - Murat Karagöz
实际上,我使用的名称只是示例,您可以使用自己的类,我只是想展示原则 :) - Hajji Tarik

1
<IconButton> 使用的图标由它的 iconClassName 属性定义。
之后它可能看起来像这样。
<IconButton key="tableModeButton" 
  onTouchTap={() => { 
     this.setState( prevState => {isCardView: !prevState.isCardView} ) }
  }
  iconClassName={this.state.isCardView ? "view_module" : "list"} />
</IconButton>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接