react/refs 正确性
功能
验证 refs 的正确用法:不得在渲染期间读取或写入 ref.current,只能在事件处理程序和 effect 中进行。
由 React Compiler 提供支持,该编译器每个文件运行一次,并与其他 React Compiler 规则共享。移植自 react-hooks/refs。
为什么这是不好的?
React 在渲染期间可能尚未附加 ref,并且读取它不会使组件订阅更新——UI 会在不知不觉中过时。
示例
此规则中不正确的代码示例:
jsx
import { useRef } from "react";
function Component() {
const ref = useRef(null);
const value = ref.current; // read during render
return <div>{value}</div>;
}此规则中正确的代码示例:
jsx
import { useEffect, useRef } from "react";
function Component() {
const ref = useRef(null);
useEffect(() => {
ref.current.focus();
}, []);
return <input ref={ref} />;
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/refs": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/refs": "error",
},
});bash
oxlint --deny react/refs --react-plugin版本
此规则在 vnext 中添加。
