在函数组件中使用createRef
几乎肯定是个错误。您可能需要使用useRef
来代替。这很容易导致令人困惑的bug。例如,请参阅这个流行的“堆栈溢出”问题。
完全班宁createRef
会在类组件上产生误报。我建议添加一个规则,专门在eslint-plugin-react(jsx-eslint/eslint-plugin-react#2966)的函数组件中标记这一点,但他们建议我在这里提交一个问题。
React版本:16.13.1时的React
重现步骤
1.设置eslint-plugin-react-hooks并创建一个使用React.createRef
的函数组件。
1.没有任何抱怨。
链接到代码示例:https://codesandbox.io/s/cool-volhard-9zj0s
export default function App() {
const ref = React.createRef(0);
// Change to this to make the example work as intended:
// const ref = React.useRef(0);
const [, update] = React.useState(0);
const handleClick = () => {
ref.current += 1;
update((n) => n + 1);
};
React.useEffect(() => {
ref.current = 0;
}, [ref]);
return (
<div className="App" ref={ref}>
<h1>Hello CodeSandbox</h1>
<h2>Value is {ref.current}</h2>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
当前行为
eslint-plugin-react-hooks不会报告问题。
预期行为
eslint-plugin-react-hooks应该报告一个问题,即createRef
应该是useRef
。
2条答案
按热度按时间hk8txs481#
IMO这看起来确实像是应该警告的事情,但是
eslint-plugin-react-hooks
警告它也似乎很奇怪(因为那些规则都是关于钩子的,而createRef
不是钩子)。piwo6bdm2#
useRef是一个钩子,这是一个关于将用例迁移到钩子的规则,这似乎是合适的。