我正在尝试在我的应用程序中使用react-timeout,我在TypeScript中编写。我在文档中关注the "Light Switch" example,其中setTimeout
函数似乎在导入ReactTimeout
时被定义为prop。我从文档中的这一行示例中收集了这些内容:
handleClick = (e) => {
this.props.setTimeout(this.toggle, 5000) // call the `toggle` function after 5000ms
}
但是,当我类似地实现它时,TypeScript抱怨该属性不存在。这里(基本上)是我的代码。错误在注释中注明:
import * as React from 'react';
import Axios from 'axios';
import ReactTimeout from 'react-timeout';
export interface ExampleProps {
// none at this point
}
export interface ExampleState {
isSearching: boolean;
searchString: string;
}
export default class Example extends React.Component<ExampleProps, ExampleState> {
constructor (props: ExampleProps) {
super(props);
this.state = {
isSearching: false,
searchString: undefined
}
this.onSearchChange = this.onSearchChange.bind(this);
}
onSearchChange(e){
this.setState({searchString: e.target.value});
console.log('searchString: "%s"', this.state.searchString);
// I want to wait 3 seconds before submitting the search, to allow for typing
// ...but I get an error here:
// [ts] Property 'setTimeout' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<ExampleProps>'
this.props.setTimeout(this.doSearch(this.state.searchString), 3000);
//ReactTimeout.setTimeout(this.doSearch(this.state.searchString), 3000);
// calling it directly like this doesn't work either: "Uncaught TypeError: Cannot read property 'setTimeout' of undefined"
}
doSearch(searchTerm) {
this.setState({isSearching: true});
console.log('Now I will go search for "%s"...', searchTerm);
}
render() {
const {
isSearching
} = this.state;
return (
<div>
<h2>Search</h2>
<input type="text" name="searchString" onChange={this.onSearchChange} />
{
isSearching ? <span>Searching...</span> : <span> </span>
}
</div>
)
}
}
错误信息对我很清楚:setTimeout
根本不在道具中;但我不知道如何定义它。如果我使用React.Component<any, ExampleState>
创建我的类,TypeScript不再抱怨,但我收到运行时错误,&#34;未捕获TypeError:this.props.setTimeout不是函数&#34; 鉴于之前的信息,这并不令人惊讶。
如何从此库中明确设置对setTimeout
的引用?我需要在ExampleProps
中执行此操作吗?如果是这样,怎么样?
答案 0 :(得分:0)
react-timeout是一个所谓的HOC组件,请参阅:https://reactjs.org/docs/higher-order-components.html
因此,为了让react-timeout组件将它传递给你的组件,你必须将你的组件包装在react-timeout组件中,这通常是通过将它包装在导出中完成的,你可以看到这在https://github.com/plougsgaard/react-timeout的示例中。
基本上尝试删除default export
前面的class example
和文件的最后一行default export ReactTimeout(example)