那么这是同样的问题,还是我只是遗漏了什么?
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
当我在接口中定义 MyComponent 的 props 时,我收到以下错误:
错误 TS2339:属性“onChange”在类型“IntrinsicAttributes & Props”上不存在。
但是,如果我将 props 类型更改为 any,它就可以正常编译。
const MyComponent = (props: any) => {
是否可以在接口中定义 props 以便有特定的 props 是必需的,但也允许传入额外的 props 这样我就不必显式地将它们添加到接口中?
我使用的是 TypeScript 2.3.4 和 React 15.5.4。