[英]How to innerHTML a jsx element on react
我一直在尝试制作一个登录表单,当你点击注册时,注册按钮变成一个加载图标,如果它从服务器得到false
响应,它会再次加载按钮而不是加载微调器,但我遇到了问题当它应该删除加载微调器并再次显示注册按钮(使用innerHTML
)时,它只显示 [object Object] 而不是按钮,所以这里是我用来呈现按钮微调器的语句:
onSubmit = () => {
document.getElementById('error-alert').innerHTML = "";
document.getElementById('sumbit-btn').innerHTML = ` //rendering the loading spinner
<span class="btn btn-light border-1 border-dark mdi mdi-loading mdi-spin mdi-24px"></span>`;
fetch("my server link here", {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
name: this.state.name
})
})
.then(response => response.json())
.then(user => {
if (user.id) { // if the input is correct (response true from the server)
this.props.loadUser(user)
this.props.onRouteChange('home');
}
else { //if the response is false from the server
/////////////// this is the innerHTML i mean: //////////
document.getElementById('sumbit-btn').innerHTML =
<div
className="btn btn-light border-1 border-dark"
onClick={this.onSubmit}
>Register
</div>
///////////////////////////////////////////////////////////
}
})
}
请注意,此代码块位于render(){}
我认为最简单的方法是在 state 中存储一个布尔值,然后在渲染中创建一个三元。 根据您的需要更改布尔值。
onSubmit = () => {
document.getElementById('error-alert').innerHTML = "";
this.setState({showLoading: true});
<span class="btn btn-light border-1 border-dark mdi mdi-loading mdi-spin mdi-24px"></span>`;
fetch("my server link here", {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
name: this.state.name
})
})
.then(response => response.json())
.then(user => {
if (user.id) { // if the input is correct (response true from the server)
this.props.loadUser(user)
this.props.onRouteChange('home');
} else {
this.setState({showLoading: false});
}
render(){
return(
<div>{show ?
<Loading/>
:
<div
className="btn btn-light border-1 border-dark"
onClick={this.onSubmit}
>Register
</div>
}
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.