单击按钮时的加载指示器(反应和 ant 设计)



我做了一个按钮,点击后将其标签从"提取"更改为"提取",然后它被禁用。我现在想做的是让它在单击时有一个加载指示器,并在按钮被禁用时停止。

我试过了

document.getElementById(inputID).setAttribute("load", "true");

当单击按钮但发现它不适用于按钮时。我现在也在尝试将 setState 与我的

document.getElementById("btnTesting").innerHTML = "EXTRACTED";

class DashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
}
onClickBtn = () => {
this.setState({ loading: true});
document.getElementById("btnTesting").innerHTML = "EXTRACTED";
document.getElementById("btnTesting").setAttribute("disabled","true");
}
render() {
return (
<Button id="btnTesting" onClick={this.onClickBtn} loading={this.state.loading}>EXTRACT</Button>
)
}
}

我希望在单击时有一个加载指示器,然后在按钮禁用时停止。但是屏幕变成空白。我在控制台中查看并看到此错误

未捕获的 DOMException:无法在"节点"上执行"insertBefore":要在其之前插入新节点的节点不是此节点的子节点。

组件中发生上述错误: 等等。 等等。

未捕获的 DOMException:无法在"节点"上执行"insertBefore":要在其之前插入新节点的节点不是此节点的子节点。

因为你使用的是 React,所以你不需要使用innerHTMLsetAttribute来更改按钮文本或禁用状态。

您可以使用状态变量buttonText,初始化为"提取"并isDisabled,初始化为 false,并且可以在按钮完成执行后更改状态。

class DashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
buttonText: "EXTRACT",
isDisabled: false
};
}
onClickBtn = () => {
this.setState({ loading: true });
setTimeout(() => {
this.setState({
buttonText: "EXTRACTED",
isDisabled: true,
loading: false
});
}, 2000);
};
render() {
return (
<Button
id="btnTesting"
onClick={this.onClickBtn}
loading={this.state.loading}
disabled={this.state.isDisabled}
>
{this.state.buttonText}
</Button>
);
}
}

我添加了 2000ms 的设置超时,以便您可以看到加载指示器。

在此处查找演示:https://codesandbox.io/s/antd-reproduction-template-l1d4r

你能检查下面的代码是否解决了你的问题吗?我添加了计时器来演示时间影响,以便加载变得明显。

使用ReactJS,您不必使用 setAttribute 或 innerHTML,因为 ReactJS 使用 virtualDOM。即使你使用它们,它也会使 DOM 处于不一致的状态。 根据标准的 React 实践,您应该使用状态变量处理您的需求(即更改 DOM)

class DashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: {"btn1": false},
disabled: false,
buttonText: 'Extract'
}
onClickBtn = (btnStr) => {
let loadingCopy = Object.assign({},this.state.loading)
loadingCopy[btnStr] = true
this.setState({loading: loadingCopy})
setInterval(() => {
loadingCopy[btnStr] = false
this.setState({ loading: loadingCopy, buttonText: 'Extracted', disabled: true });
}, 3000);
}
render() {
return (
<ButtononClick={() =>this.onClickBtn("btn1")} loading={this.state.loading["btn1"]} disabled={this.state.disabled}>{this.state.buttonText}</Button>
)
}
}
import { Button } from 'antd';
import React from "react";
class SubmitButton extends React.Component {
state = {
loadings: [],
};
enterLoading = index => {
this.setState(({loadings}) => {
const newLoadings = [...loadings];
newLoadings[index] = true;
return {
loadings: newLoadings,
};
});
};
render() {
const {loadings} = this.state;
return (
<>
<Button type="primary" htmlType="submit" loading={loadings[0]} onClick={() => this.enterLoading(0)}>
Submit
</Button>
</>
);
}

法典: https://codesandbox.io/s/withered-framework-w5lmc?file=/src/App.js

最新更新