问题
I'm using Reactstrap with Typescript and typings from @types/reactstrap. I'm trying to use the Button component in an HOC, so I need to explicitly reference the ButtonProps type. Here's the code for it:
import React from 'react'
import {withFormState, FormState} from 'informed'
import {Button, ButtonProps} from 'reactstrap'
export const SubmitButton = withFormState<Button, {formState: FormState} & ButtonProps>(
({
formState: {pristine, invalid},
disabled = false, children,
...props
}) =>
<Button type="submit" color="success"
disabled={pristine || invalid || disabled}
{...props}>
{children}
</Button>
)
So basically I just combine ButtonProps from the package with FormState from another package, but in the end the props variable should have only the props matching the ButtonProps type (since formState is destructured from it).
However, TS says that ButtonProps do not match the props that I pass to the component, namely that the ref property types are incompatible. I don't work with refs in this instance, so it's unlikely that I messed them up. Most likely, I just do not understand how to properly define types in this case.
Here are the references to the typings that I use:
- Informed's withFormState type
- Reactstrap's ButtonProps and Button
回答1:
I'd consider this a bug in the @types/reactstrap type declarations. Notice that the same error occurs in the following simpler test case:
function test(props: ButtonProps) {
return <Button {...props}/>;
}
ButtonProps includes React.HTMLProps<HTMLButtonElement>, which includes a ref prop of type Ref<HTMLButtonElement>, but Button cannot truly accept such a prop because React will intercept a ref prop specified on the JSX element and associate it with the Button component, not any HTMLButtonElement that may exist within it. ButtonProps should probably be changed to use React.AllHTMLAttributes<HTMLButtonElement> instead of React.HTMLProps<HTMLButtonElement>. Please file an issue against DefinitelyTyped.
As a workaround, you can remove the bogus ref prop in the destructuring:
export const SubmitButton = withFormState<Button, {formState: FormState} & ButtonProps>(
({
formState: {pristine, invalid},
disabled = false, children,
ref, // <---
...props
}) => {
return <Button type="submit" color="success"
disabled={pristine || invalid || disabled}
{...props}>
{children}
</Button>
}
)
来源:https://stackoverflow.com/questions/52728722/buttonprops-from-the-package-is-incompatible-with-button-component-from-the-pack