gpt4 book ai didi

javascript - 如何在react上innerHTML jsx元素

转载 作者:行者123 更新时间:2023-12-02 21:22:06 25 4
gpt4 key购买 nike

我一直在尝试制作一个登录表单,当您单击注册时,注册按钮会变成加载图标,如果它从服务器收到 false 响应,则会再次加载按钮的加载微调器,但我遇到一个问题,当它应该删除加载微调器并再次显示注册按钮时,它只显示 [object Object] 而不是按钮(使用 innerHTML),所以这是我用来渲染按钮、微调器的语句:

     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(){} 之外

最佳答案

我认为最简单的方法是在状态中存储一个 bool 值,然后在渲染中创建一个三元值。根据您的需要更改 bool 值。

 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>
}
)
}

关于javascript - 如何在react上innerHTML jsx元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60818299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com