在使用ref的过程中,我需要通过ref来动态给元素的设置style,因此在此对ref有一个类型声明为:
bgImage:React.RefObject<HTMLDivElement>;
constructor(props:MusicListProps){
super(props)
this.bgImage = React.createRef();
this.state = {
minTransalteY : 0,
imageHeight: 0
}
}
该组件很多方法中都用到了这个ref,并且每次方法中都需要用一个判断this.bgImage.current是否为null,如果为null则返回,这样可以新增一个方法用于复用。
或者第二种方法在this.bgImage.current上加一个!,提示typescript这里不可能会是null或者undefined
请问除了上述妥协的解决办法,还有什么更好的方法在typescript中对ref类型声明吗?
componentDidMount(){
if(!this.bgImage.current){
console.log("this.bgImage.current",this.bgImage.current)
return
}
let listTop = this.bgImage.current.clientHeight;
this.list.current.wrapper.current.style.top = `${listTop}px`;
this.setState({
imageHeight: listTop,
minTransalteY: -listTop + RESERVED_HEIGHT
})
}
typescript作为类型语言,就是为了可以提供尽可能严格的类型检测,所以办法无非就是你上述提到的两种:要不判断,要不加!
typescript写起来真的会让人感觉很麻烦,这也算是typescript的优点带来的“缺点”吧,但为了高可维护可预测的代码,我们必须选择妥协,不然还是用js写吧。