vlk*_*vlk 12 typescript reactjs styled-components react-hooks
我在使用useRef
带有样式组件的钩子时遇到了一些问题。
Linter 提醒我Object is possibly 'null'
在 didMount 中useEffect
。对此有什么想法吗?
ref
在类组件中使用的,这是在 React 钩子之前使用它的唯一方法,innerRef
道具是不是在风格组件的当前版本支持了。这是我的组件的示例片段:
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}/>
);
}
Run Code Online (Sandbox Code Playgroud)
vlk*_*vlk 17
我终于找到了解决方案:
const inputRef = useRef() as React.MutableRefObject<HTMLInputElement>;
Run Code Online (Sandbox Code Playgroud)
这个对我有用:
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}/>
);
}
Run Code Online (Sandbox Code Playgroud)
作为当前接受的答案的替代方案,您还可以执行以下操作:
const inputRef = useRef<HTMLInputElement>(null);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8447 次 |
最近记录: |