【发布时间】:2020-02-26 09:23:06
【问题描述】:
习惯于 React 函数组件,我通常在函数内部声明 const。但是现在我必须在类组件中声明一个变量,并尝试了三种不同的方式:
constructor(props: HWTrendChartProps) {
super(props);
testVarible = 'this is a test'; // 'testVarible' is not defined.eslint(no-undef)
}
constructor(props: HWTrendChartProps) {
super(props);
this.testVarible = 'this is a test'; // Property 'testVarible' does not exist on type 'classname'.ts(2339)
}
private static timeoutRef: any; // works but have to re-assign using classname.timeoutRef = blahblah;
我正在尝试将setTimeout 引用存储在类组件中,以便我可以从componentWillUnmount 中获取clearTimeout。如果可以避免,我不想添加它。
【问题讨论】:
-
在构造函数中使用状态 constructor(props: HWTrendChartProps) { super(props); this.state={ testVarible: '这是一个测试'; } } 然后通过键入 this.state.testVariable 访问它
-
您尝试的第二种类型应该可以工作,在小提琴中也为我工作。我认为您调用 setTimeout 的方式存在一些问题。您可以发布您调用 setTimeout 的部分吗?
标签: reactjs typescript settimeout