如何在React可复用组件中根据条件显示特定文本?解决Bar组件同时展示百分比与limit/total值的问题
解决Bar组件同时显示百分比和limit/total的问题
嘿,这个问题很常见——你现在的逻辑是让showValue和showCompleted两个条件各自独立判断,而showValue的默认值是!indeterminate(通常indeterminate默认是false,所以showValue默认就是true),所以当你在父组件里传了showCompleted={true}时,两个条件都满足,自然会同时渲染。
咱们可以从两个方向来修复,根据你的需求选最合适的:
方案1:快速互斥修复(改动最小)
直接让两个显示逻辑互斥,当showCompleted为true时,就不渲染百分比内容。同时在父组件调用时显式关闭showValue,避免默认值干扰:
修改Bar组件的渲染逻辑:
const Bar = ({ label, indeterminate, showCompleted = false, // 给个默认值避免未传时的问题 limit, total, showValue = !indeterminate, value, max = 100, ...rest }: BarProps) => ( <BarWrapper {...rest}> <Wrapper> <Progress value={value} max={max} /> {indeterminate && <span />} {/* 只有当showValue为true且showCompleted为false时,才显示百分比 */} {showValue && !showCompleted && ( <span> {value} <Unit>%</Unit> </span> )} {showCompleted && ( <span>{limit}/{total}</span> )} </Wrapper> {label && <Label>{label}</Label>} </BarWrapper> );
父组件调用时显式关闭showValue:
const ParentComponent = () => { const limit = "10"; const total= "15"; return( <Bar showCompleted showValue={false} limit={limit} total={total} /> ); }
方案2:用枚举模式控制(更优雅,扩展性强)
如果未来可能有更多显示格式需求,建议用一个枚举类型的prop来统一控制显示模式,避免多个布尔prop带来的混乱:
第一步:更新BarProps类型定义
// 定义显示模式的枚举类型 type DisplayMode = "percentage" | "completed" | "none"; interface BarProps { label?: string; indeterminate?: boolean; displayMode?: DisplayMode; // 新增这个prop替代showValue和showCompleted limit?: string; total?: string; value?: number; max?: number; // 其他原有props... }
第二步:修改Bar组件逻辑
const Bar = ({ label, indeterminate = false, displayMode = indeterminate ? "none" : "percentage", // 默认逻辑:非 indeterminate 时显示百分比 limit, total, value, max = 100, ...rest }: BarProps) => ( <BarWrapper {...rest}> <Wrapper> <Progress value={value} max={max} /> {indeterminate && <span />} {/* 根据displayMode判断渲染内容 */} {displayMode === "percentage" && ( <span> {value} <Unit>%</Unit> </span> )} {displayMode === "completed" && ( <span>{limit}/{total}</span> )} </Wrapper> {label && <Label>{label}</Label>} </BarWrapper> );
父组件调用时指定模式
const ParentComponent = () => { const limit = "10"; const total= "15"; return( <Bar displayMode="completed" limit={limit} total={total} /> ); }
两种方案各有优势:方案1改动小,适合快速修复现有问题;方案2更清晰,能避免后续新增显示格式时出现类似的布尔prop冲突问题。
内容的提问来源于stack exchange,提问作者stackuser
相关产品推荐
相关产品推荐

