React:带微调器的按钮,如何知道动画何时应该停止



我想创建一个自定义按钮组件,当按下它时,它会在自己内部显示一个加载微调器,并具有一个可以外部定义的条件,该条件将告诉按钮删除微调器并返回其原始外观。类似这样的东西:

<CustomButton
type="button"
className="btn btn-primary"
stopSpinningWhen={condition}
onClick={() => ...}
>
Click me
</CustomButton>

目前,我的带有微调器的按钮看起来是这样的,这非常好,但为每个按钮编写重复的代码/状态是一件痛苦的事:

const [buttonSpinner, setButtonSpinner] = useState(false);
const onClickEvent = (ev) => {
setButtonSpinner(true);
if (condition) {
setButtonSpinner(false);
}
};
return (
<button
type="button"
className="btn btn-primary"
onClick={onClickEvent}
disabled={buttonSpinner}
>
{buttonSpinner ? (
<span
className="spinner-border spinner-border-sm"
role="status"
aria-hidden="true"
></span>
) : (
"Click me"
)}
</button>
);

我使用的是React 17.0.2。

这可能吗?

您可以创建自己的自定义按钮,该按钮还可以接收isLoading

const Spinner = (
<span
className="spinner-border spinner-border-sm"
role="status"
aria-hidden="true"
/>
)
const CustomButton = (props) => (
<button
type="button"
className="btn btn-primary"
onClick={props.onClick}
disabled={props.isLoading}
>
{props.isLoading ? <Spinner /> : "Click me"}
</button>
)
const YourComponent = () => {
const [isLoading, setIsLoading] = useState(false)
const onClick = async (event) => {
setIsLoading(true)
doHeavyTask()
setIsLoading(false)
}
return (
<div>
<CustomButton isLoading={isLoading} onClick={onClick} />
</div>
)
}

您使用加载属性作为条件,并将其作为道具传递给自定义按钮组件。类似这样的东西:

const myComponent = () =>{
const [loading, setLoading] = useState(false)
const myFunc = async () = {
setLoading(true)
//call api or do seomthing, after the process finishes set loading to false again
const resp = await fetch("myAPIURL")
console.log(resp.data)
setLoading(false)
}
return(
<CustomButton
type="button"
className="btn btn-primary"
spinning={loading}
onClick={() => myFunc()}
>
Click me
</CustomButton>
)
}

相关内容

最新更新