使用 react-autosuggest
时出现此 Typescript 错误使用自定义输入样式组件。
Types of property 'onChange' are incompatible. Type '(event: FormEvent, params: ChangeEvent) => void' is not assignable to type '(event: ChangeEvent) => void'.
代码:
(请注意,它不完整,只是相关部分)
// styled.ts
export const Input = styled.input`
// styles
`;
// index.tsx
function renderInput(
inputProps: Autosuggest.InputProps<SuggestionSearch>,
placeholder: string
) {
// --> error here
return <Input {...inputProps} placeholder={placeholder} />;
}
const MyComponent = () => {
const autosuggestRef = React.useRef<
Autosuggest<SuggestionSearch, SuggestionSearch>
>(null);
const onChange = (event: React.FormEvent, { newValue }: ChangeEvent) =>
setValue(newValue);
const inputProps = {
value,
onChange,
onKeyPress: onEnterPress,
};
return (
<Autosuggest
ref={autosuggestRef}
renderInputComponent={props => renderInput(props, placeholder)}
inputProps={inputProps}
// other props
/>
)
}
不确定如何解决此问题,因为 Autosuggest onChange 函数会覆盖基本输入 onChange Prop 。
最佳答案
我自己花了整晚的时间来解决这个问题。看来这是一个错误。这是 InputProps
的签名:
interface InputProps<TSuggestion>
extends Omit<React.InputHTMLAttributes<any>, 'onChange' | 'onBlur'> {
onChange(event: React.FormEvent<any>, params: ChangeEvent): void;
onBlur?(event: React.FocusEvent<any>, params?: BlurEvent<TSuggestion>): void;
value: string;
}
看来我们需要创建自己的
Input
采用这种类型 onChange
的组件签名或将此 onChange 包装在标准 onChange 中。所以,这是我的方法:
const renderInputComponent = (inputProps: InputProps<TSuggestion>): React.ReactNode => {
const onChangeHandler = (event: React.ChangeEvent<HTMLInputElement>): void => {
inputProps.onChange(event, { newValue: event.target.value, method: 'type' });
};
return <Input {...inputProps} onChange={onChangeHandler} />;
}
两个潜在的错误:
event
返回的是 React.ChangeEvent
而不是 React.FormEvent
.微小的差异,但如果您实际使用它并且对事件足够特别,它可能会在运行时出现问题。 params: ChangeEvent
只占type
事件方法。如果你想要其他的,比如click、esc等等……你必须自己补充(例如通过onKeyUp
,然后调用`onChange(...{method: 'esc'}) 根据文档:
Note: When using renderInputComponent, you still need to specify the usual inputProps. Autosuggest will merge the inputProps that you provide with other props that are needed for accessibility (e.g. 'aria-activedescendant'), and will pass the merged inputProps to renderInputComponent.
你不必这样做:
renderInputComponent={props => renderInput(props, placeholder)}
只需通过
placeholder
直接进入您的inputProps
这将在 renderInputComponent
中直接返回给您. const inputProps = {
value,
onChange,
onKeyPress: onEnterPress,
placeholder: 'something!`
};
关于javascript - Autosuggest renderInputComponent - inputProps 类型的属性 'onChange' 不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61785523/