React ChakraUI forwardRef封装Input时variant属性失效问题
问题原因
属性展开顺序错误导致自定义配置被覆盖。JSX 中后声明的属性会覆盖前面的同名字段,你手动设置的variant="flushed"放在了{...props}之前,会被 props 中携带的 Input 组件默认 variant(outline)覆盖。
解决方案
调整属性顺序,将需要固定的配置项放在{...props}之后,确保你的固定配置优先级最高,不会被传入的 props 覆盖。同时修正 forwardRef 泛型的顺序,符合 React 和 Chakra UI 的类型规范。
修复后代码如下:
import { forwardRef, InputProps, Input } from '@chakra-ui/react'; const ModalInput = forwardRef<HTMLInputElement, InputProps>((props, ref) => ( <Input ref={ref} {...props} color="gray.600" variant="flushed" > {props.children} </Input> )); export default ModalInput;
如果后续需要允许使用方自定义 variant 覆盖默认的 flushed,只需要把variant="flushed"调整回{...props}之前即可。
内容的提问来源于stack exchange,提问作者AntoineLB
相关产品推荐
相关产品推荐

