React:如何在单击后禁用按钮
下面的这个例子展示了如何在 React 中单击某个按钮后禁用它。这在您希望防止用户重复点击多次的情况下很有用,例如提交表单、以促销价格购买产品(每人只能购买一个)等。
示例预览
完整代码 ( 带解释):
// KindaCode.com
// src/App.js
import { useState } from 'react';
function App() {
// this determines whether the button is disabled or not
const [isDisabled, setIsDisabled] = useState(false);
// This function is called when the button is clicked the first time
const handleClick = () => {
alert('Hi there!');
setIsDisabled(true);
};
return (
<div style={styles.container}>
<button
disabled={isDisabled}
onClick={handleClick}
// this is the style for the button
style={isDisabled ? styles.buttonDisabled : styles.button}
>
Button
</button>
</div>
);
}
// Styles
const styles = {
container: {
width: '100vw',
height: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
button: {
padding: '10px 30px',
cursor: 'pointer',
},
buttonDisabled: {
padding: '10px 30px',
cursor: 'not-allowed',
},
};
export default App;
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。