React如何启用已禁用的按钮?多按钮联动启用功能实现咨询
解决方案
核心调整说明
你需要先把App组件内的静态变量替换为响应式的useState状态,这样状态变更时组件才会重新渲染更新按钮状态。
完整修改后的代码
import React, { useState } from "https://cdn.skypack.dev/react@17.0.1"; import ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1"; // 小优化:React中指定DOM类名用className,避免原生class属性的命名冲突警告 function Button({ isLocked, children, ...other }) { const className = isLocked ? "button button--locked" : "button"; return ( <button className={className} disabled={isLocked} {...other}> {isLocked ? "哦不!我被锁住了:(" : children} </button> ); } function App() { // 替换为响应式状态 const [isButtonBLocked, setIsButtonBLocked] = useState(true); const [bClickCount, setBClickCount] = useState(0); const [isButtonCLocked, setIsButtonCLocked] = useState(true); const TOTAL_NEED_CLICK = 5; const unlockSecondButton = () => { // 点击A按钮后解锁B setIsButtonBLocked(false); }; const unlockThirdButton = () => { // 累计B按钮点击次数 setBClickCount(prevCount => { const newCount = prevCount + 1; // 点击次数达到5次时解锁C if (newCount === TOTAL_NEED_CLICK) { setIsButtonCLocked(false); } return newCount; }); }; return ( <> {/* 按钮A */} <Button onClick={unlockSecondButton}> 点击我解锁第二个按钮 </Button> {/* 按钮B */} <Button onClick={unlockThirdButton} isLocked={isButtonBLocked}> 再点击{TOTAL_NEED_CLICK - bClickCount}次即可解锁第三个按钮 </Button> {/* 按钮C */} <Button isLocked={isButtonCLocked}>耶!我解锁了:)</Button> </> ); } ReactDOM.render(<App />, document.getElementById("root"));
逻辑说明
- 点击按钮A时触发
unlockSecondButton,直接修改isButtonBLocked为false,按钮B的disabled属性失效,完成解锁 - 每次点击按钮B时触发
unlockThirdButton,先更新B的点击计数,计数达到预设的5次时修改isButtonCLocked为false,解锁按钮C - 按钮B的文本会动态显示剩余需要点击的次数,更符合交互逻辑
内容的提问来源于stack exchange,提问作者yungbruhM
相关产品推荐
相关产品推荐

