请判断我的代码是否符合您的要求.
import { useState } from "react";
const Button = ({ children, loading, disabled, onClick }) => {
return (
<button disabled={disabled} onClick={onClick}>
{loading ? "Loading..." : children}
</button>
);
};
const ButtonWrapper = ({ url, onFetching, disabled, children }) => {
const [loading, setLoading] = useState(false);
const [data, setData] = useState();
const getData = () => {
setLoading(true);
onFetching(true);
fetch(url)
.then((response) => response.json())
.then((json) => setData(json))
.finally(() => {
setLoading(false);
onFetching(false);
});
};
return (
<Button loading={loading} disabled={disabled} onClick={() => getData()}>
{children}
</Button>
);
};
export default function App() {
const [isFetching, setIsFetching] = useState(false);
return (
<div className="App">
<ButtonWrapper
onFetching={setIsFetching}
disabled={isFetching}
url="https://jsonplaceholder.typicode.com/posts"
>
Fetch Posts
</ButtonWrapper>
<ButtonWrapper
onFetching={setIsFetching}
disabled={isFetching}
url="https://jsonplaceholder.typicode.com/albums"
>
Fetch Albums
</ButtonWrapper>
<ButtonWrapper
onFetching={setIsFetching}
disabled={isFetching}
url="https://jsonplaceholder.typicode.com/users"
>
Fetch Users
</ButtonWrapper>
</div>
);
}
我已经在相同的文件中编码,但你可以制作一个单独的文件,也确保改变网络网络节流,以降低3G或其他什么,以清楚地看到功能.
演示:https://codesandbox.io/s/cranky-shannon-vtwmz8?file=/src/App.js