我刚开始使用TypeScript,遇到了一个错误。通常我在构造函数中初始化 refs,但 TypeScript 不喜欢它,请考虑一下:
class MyComponent extends React.PureComponent<types.MyComponentProps>
constructor(props: MyComponentProps){
super(props);
// error here: Property 'target' does not exist on type 'MyComponent'
this.target = React.createRef();
}
}
我知道React.PureComponent
接受 props 的参数和状态的参数,但我如何TypeScript
知道我的组件应该直接期望属性,例如 refs?或者,这是一种反模式,我应该以不同的方式定义引用吗?
您应该将target
初始化为类属性:
class MyComponent extends React.PureComponent<types.MyComponentProps>
target = React.createRef();
constructor(props: MyComponentProps){
super(props);
// May not need a constructor at all
}
}
这就是我的做法,这样您就可以获得参考文献的所有必要类型信息。例如:滚动视图
interface Props {}
interface State {}
class SomeComponent extends React.PureComponent<Props, State> {
private target: React.RefObject<ScrollView>; // or some other type of Component
constructor(props: Props){
super(props);
this.target = React.createRef();
}
public render(): JSX.Element {
return (
<ScrollView ref={this.target}>
...
</ScrollView>
);
}
// now you can define a scrollToTop method for instance
private scrollToTop = (): void => {
// The scrollTo method is available from autocomplete since it was defined as a ScrollView ref
this.scrollViewRef.current.scrollTo({ x: 0, y: 0, animated});
}
}
你在构造函数中声明了错误的目标,这样做是这样的
class MyComponent extends React.PureComponent<types.MyComponentProps>
constructor(props: MyComponentProps){
super(props);
}
this.target = React.createRef();
}