基于typescript的react项目中Ref的类型确定的一个疑问!

在使用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
        })
    }
阅读 9.9k
2 个回答

typescript作为类型语言,就是为了可以提供尽可能严格的类型检测,所以办法无非就是你上述提到的两种:要不判断,要不加!

typescript写起来真的会让人感觉很麻烦,这也算是typescript的优点带来的“缺点”吧,但为了高可维护可预测的代码,我们必须选择妥协,不然还是用js写吧。

加!更正确. tsc不会知道一个react ref 在特定时机"应该"不是null, 写的人应该自己保证.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题