【问题标题】:React hook useRef not working with styled-components and typescriptReact hook useRef 不适用于样式化组件和打字稿
【发布时间】:2020-01-22 20:51:07
【问题描述】:

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

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

这不是重复的,原因有两个:

  • 旧答案是指在类组件中使用的ref,这是在 React 钩子之前使用它的唯一方法,
  • 当前版本的样式化组件不再支持 innerRef 属性。

这是我的组件的示例 sn-p:

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}/>
  );
}

【问题讨论】:

  • @MatthewBarbara innerRef 不再被样式化组件支持

标签: reactjs typescript react-hooks styled-components


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我终于找到了解决办法:

    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}/>
      );
    }
    

    【讨论】:

    • 您实际上可以在输入参数中传递HTMLInputElementconst inputRef = &lt;HTMLInputElement&gt;useRef() 而不是使用as
    • 我不断收到错误消息“无法为函数组件提供引用。尝试访问此引用将失败。您是要使用 React.forwardRef() 吗?”
    • useRef 有一个泛型允许将类型另外修改为默认值:const inputRef = useRef&lt;HTMLInputElement&gt;() 导致React.MutableRefObject&lt;HTMLInputElement | null | undefined&gt;
    • 你如何在纯 Javascript 中做到这一点?
    【解决方案3】:

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

    const inputRef = useRef<HTMLInputElement>(null);
    

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 2021-06-07
      • 1970-01-01
      • 2019-06-19
      • 2021-05-01
      • 1970-01-01
      • 2022-01-08
      • 2020-11-02
      • 2021-01-23
      相关资源
      最近更新 更多