在我的课堂上,我将按钮文本设置为状态:
constructor(props) {
super(props);
this.state = {
buttonText: 'LOGIN',
};
}
按钮标记如下:
<button type="submit" className="btn btn-lg btn-primary w-100 my-2">{this.state.buttonText}</button>
我试图buttonText
通过通过函数更改值来动态地将文本更改为 FA 图标:
onSubmit(e) {
e.preventDefault();
this.setState({
buttonText: '<i className="fa fa-spinner" aria-hidden="true" />',
});
axios.post('/api/authentication/login', { username: this.state.username, password: this.state.password })
.then((response) => {
this.props.onLogin(response.data);
this.props.toggle();
});
}
这是有效的,因为按钮会使用新文本重新呈现;但是,它不是 FA 图标,而是使用标记呈现,即<i className="fa fa-spinner" aria-hidden="true" />
在按钮的标题中显示为原始文本。我究竟做错了什么?
您当前的解决方案通过输入 html 动态更改 DOM。这可以通过危险的SetInnerHTML来实现,但是当有完全可行的解决方案可用时,我不推荐它:
我建议您创建一个元素并切换它是否通过您所在州的布尔属性呈现。例如{loading:false}
<i className="..." style={this.state.loading ? {display:'inline'} : {display:'none'}} />
然后让您的 onSubmit 方法loading
在您的状态下正确切换
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句