如何获取React-Bootstrap中Form.Control的Props类型并解决autoFocus属性类型报错问题
I've run into this exact issue before when wrapping React Bootstrap components with styled-components—getting the right type for props can be tricky when you need both library-specific props and native HTML element props. Let's fix your type definition problem step by step.
The Root of the Issue
Your attempts with FormControlProps alone don't work because it only includes React Bootstrap's custom props, not the native HTML attributes like autoFocus that apply to inputs, selects, etc. The other type attempts either target the component itself instead of its props, or use incorrect type references.
The Fix: Use ComponentProps to Extract Full Props Type
The simplest and most reliable way to get the complete set of props that Form.Control accepts is to use React's ComponentProps utility type. It automatically extracts all props that the target component accepts, including both React Bootstrap's custom props and native HTML element props.
Here's your updated code:
import styled from "styled-components"; import { Form } from "react-bootstrap"; import type { ComponentProps } from "react"; const Styled_FormControl = styled(Form.Control)` font-size: 0.8125rem; color: #828282; `; export const FormControl = (props: ComponentProps<typeof Form.Control>) => ( <Styled_FormControl className={`${props.className || ""} form-control`} {...props} /> );
Why This Works
ComponentProps<typeof Form.Control>grabs every prop that the originalForm.Controlaccepts, including:- React Bootstrap-specific props like
as,size, orisValid - Native HTML attributes like
autoFocus,disabled,placeholder, etc., that vary depending on the element you're rendering (input, select, textarea)
- React Bootstrap-specific props like
- When you use
<FormControl autoFocus as="select" />, TypeScript will correctly recognizeautoFocusas a valid prop for a<select>element, sinceComponentPropsaccounts for theasprop's impact on valid attributes.
Why Your Previous Attempts Failed
Let's quickly break down why the types you tried didn't work:
props: typeof Form.Control: This targets the component's type itself, not the props it accepts.props: typeof Form.Control.props: Function components don't have a staticpropsproperty, so this is invalid.props: FormControlProps: As mentioned, this only includes React Bootstrap's custom props, not native HTML attributes.props: typeof FormControlProps: This refers to the type of theFormControlPropsinterface, not the props type itself.BsPrefixRefForwardingComponent<...>: This is too narrow and doesn't include the full set of native element props thatForm.Controlsupports.
Now your custom FormControl component should work with all valid props, and VS Code will stop throwing those type errors!
内容的提问来源于stack exchange,提问作者Lucas Steffen

