React hook useRef 不适用于样式组件和打字稿

React hook useRef not working with styled-components and typescript

我在使用带样式组件的 useRef 挂钩时遇到了一些问题。

Linter 提醒我 Object is possibly 'null' 在 didMount useEffect 中。对此有什么想法吗?

这不是重复的,原因有二:

这是我的组件的示例片段:

import React, { useRef, useEffect } from 'react';
import styled from 'styled-components';

const StyledInput = styled.input`
  background: transparent;
`

const MyForm = () => {
  const inputRef = useRef(null);
  
  useEffect(() => {
    if (inputRef && inputRef.current) {
      inputRef.current.focus(); //Object is possibly 'null'
    }
  }, []);

  return (
    <StyledInput ref={inputRef}/>
  );
}

在 useEffect 的数组参数中传递你的 inputRef 让我们看看它是否有效,你不能保证你的 ref 中有一个 .current,所以你应该每次都 运行 效果inputRef 变化

我终于找到了解决办法:

const inputRef = useRef() as React.MutableRefObject<HTMLInputElement>;

对我有用:

import React, { useRef, useEffect } from 'react';
import styled from 'styled-components';

const StyledInput = styled.input`
  background: transparent;
`

const MyForm = () => {
  const inputRef = useRef() as React.MutableRefObject<HTMLInputElement>;

  useEffect(() => {
    if (inputRef && inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  return (
    <StyledInput ref={inputRef}/>
  );
}

作为当前接受的答案的替代方案,您还可以:

const inputRef = useRef<HTMLInputElement>(null);