我正在使用 IconButton
来自 material-ui我想在点击/触摸事件后更改按钮的图标。
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"}
仅评估一次,之后不再评估。我想如果我改变状态我会强制重新渲染?我做错了什么?
编辑:补充说 iconButton 被分配给一个变量。如果我包括 <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" />
}
BUTTON
</a>
);
}
}
class App extends React.Component {
render () {
return (
<div>
<IconButton />
</div>
);
}
}
ReactDOM.render(<App/>,document.getElementById('root'));
我正在使用 Bootstrap ,但任何图标系统都可以工作
关于javascript - ReactJs 如何在点击事件中更改按钮的图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41852930/