vic*_*nyy 9 typescript reactjs react-bootstrap
我正在使用react-bootstrap lib并且需要使用输入组件。我知道如何输入简单的输入,但有问题FormControl
class Search extends Component<Props, { searchInput: string }> {
static defaultProps = {}
state = {
searchInput: ""
}
// This one works for input
searchInputSimple = (e: React.FormEvent<HTMLInputElement>): void => {
const { getSearch } = this.props
this.setState(
{ searchInput: e.currentTarget.value },
(): void => getSearch(this.state.searchInput)
)
}
// for FormControl. What can I use exept any?
searchInput = (e: React.FormEvent<any>): void => {
const { getSearch } = this.props
this.setState(
{ searchInput: e.currentTarget.value },
(): void => getSearch(this.state.searchInput)
)
}
render() {
const { searchInput } = this.state
return (
<>
<InputGroup className="mb-3">
<FormControl placeholder="Search" value={searchInput} onChange={this.searchInput} />
</InputGroup>
<input
placeholder="Search"
value={searchInput}
onChange={this.searchInputSimple}
className="form-control"
/>
</>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我试图理解并看看FormControl.d.ts
import Feedback from './Feedback';
import { BsPrefixComponent } from './helpers';
interface FormControlProps {
innerRef?: React.LegacyRef<this>;
size?: 'sm' | 'lg';
plaintext?: boolean;
readOnly?: boolean;
disabled?: boolean;
value?: string;
onChange?: React.FormEventHandler<this>;
type?: string;
id?: string;
isValid?: boolean;
isInvalid?: boolean;
}
declare class Form<
As extends React.ReactType = 'input'
> extends BsPrefixComponent<As, FormControlProps> {
static Feedback: typeof Feedback;
}
Run Code Online (Sandbox Code Playgroud)
如果我只使用HTMLInputElement我会收到此错误
类型错误:类型“(e: FormEvent) => void”不可分配给类型“(event: FormEvent & FormControlProps>>) => void”。参数“e”和“event”的类型不兼容。类型“FormEvent & FormControlProps>>”不可分配给类型“FormEvent”。输入 'Pick, HTMLInputElement>, "children" | “表格”| “风格”| “标题” | “模式”| “参考”| “钥匙”| “默认选中”| ... 268 更多... | “width"> & BsPrefixProps<...> & FormControlProps” 缺少类型“HTMLInputElement”中的以下属性:align、autocomplete、autofocus、dirName 以及其他 245 个属性。
那么如何做到这一点而不使用任何类型呢?它应该是别名 HTMLInputElement 之类的吗?
您正在寻找 a React.ChangeEvent,而不是 a React.FormEvent:
searchInput = (e: React.ChangeEvent<HTMLInputElement>): void => {
const { value } = e.currentTarget;
const { getSearch } = this.props;
this.setState(state => ({
...state,
searchInput: value
}), (): void => getSearch(this.state.searchInput))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8058 次 |
| 最近记录: |