Rab*_*t G 4 typescript reactjs
那么这是同样的问题,还是我只是遗漏了什么?
import * as React from 'react';
interface Props {
value: string;
}
const MyComponent = (props: Props) => {
const { value, ...rest } = props;
return (
<input {...rest} type="text" value={value} />
);
}
interface ParentState {
searchText: string;
}
class ParentComponent extends React.Component<{}, ParentState> {
state: ParentState = {
searchText: ''
};
onSearchTextChanged = (e: React.FormEvent<HTMLInputElement>) => {
this.setState({
searchText: e.currentTarget.value
});
}
render() {
const { searchText } = this.state;
return (
<div>
<h2>Some Text</h2>
<MyComponent value={searchText} onChange={this.onSearchTextChanged} className="search-input" placeholder="Enter text"/>
// Errors here
</div>
)
}
}
export default ParentComponent
Run Code Online (Sandbox Code Playgroud)
当我在接口中定义 MyComponent 的 props 时,我收到以下错误:
错误 TS2339:类型“IntrinsicAttributes & Props”上不存在属性“onChange”。
但是,如果我将 props 类型更改为 any,它会编译得很好。
const MyComponent = (props: any) => {
Run Code Online (Sandbox Code Playgroud)
是否可以在接口中定义 props 以便有特定的 props 是必需的,但也允许传入额外的 props,所以我不必明确地将它们添加到接口中?
我正在使用 TypeScript 2.3.4 和 React 15.5.4。
您可以通过向界面添加字符串索引签名来避免过多的属性/属性检查:
interface Props {
value: string;
// This is a string index signature.
// This means that all properties in 'Props' are assignable to
// the empty object type ({})
[propName: string]: {};
}
Run Code Online (Sandbox Code Playgroud)
您也可以编写,[propName: string]: any但这通常会降低使用MyComponent本身的安全性。
如果要将input内部元素的所有属性转发MyComponent到 props 中MyComponent,可以查找哪些 props input(例如,在 VSCode 中,在input标签上使用 go to definition )。
interface IntrinsicElements {
....
input: React.DetailedHTMLProps<React.InputHTMLAttributes<>, HTMLInputElement>;
....
}
Run Code Online (Sandbox Code Playgroud)
我们可以将其React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>用作 props 的基本类型,我们将获得input. 由于DetailedHTMLProps只是添加ref到React.InputHTMLAttributes<HTMLInputElement>我们可以React.InputHTMLAttributes<HTMLInputElement>用作基本接口来获取input除以下属性之外的所有属性ref:
import * as React from 'react'
interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
value: string;
}
const MyComponent = (props: Props) => {
const { value, ...rest } = props;
return (
<input {...rest} type="text" value={value} />
);
}
// Usage
interface ParentState { searchText :string }
class ParentComponent extends React.Component<{}, ParentState> {
state: ParentState = {
searchText: ''
};
onSearchTextChanged = (e: React.FormEvent<HTMLInputElement>) => {
this.setState({
searchText: e.currentTarget.value
});
}
render() {
const { searchText } = this.state;
return (
<div>
<h2>Some Text</h2>
<MyComponent value={searchText} onChange={this.onSearchTextChanged} className="search-input" placeholder="Enter text"/>
</div>
)
}
}
export default ParentComponent
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5510 次 |
| 最近记录: |