
规则:unsupported-syntax
ReactAPI 参考:ESLint 插件
规则:unsupported-syntax
校验避免使用 React Compiler 不支持的语法。如有必要,你仍然可以在 React 之外使用此语法,例如在独立的工具函数中。
规则详情
React Compiler 需要静态分析你的代码以应用优化。像 eval 和 with 这样的特性使得在编译时无法静态理解代码的功能,因此编译器无法优化使用它们的组件。
无效
此规则的不正确代码示例:
js
// ❌ Using eval in component
function Component({ code }) {
const result = eval(code); // Can't be analyzed
return <div>{result}</div>;
}
// ❌ Using with statement
function Component() {
with (Math) { // Changes scope dynamically
return <div>{sin(PI / 2)}</div>;
}
}
// ❌ Dynamic property access with eval
function Component({propName}) {
const value = eval(`props.${propName}`);
return <div>{value}</div>;
}
有效
此规则的正确代码示例:
js
// ✅ Use normal property access
function Component({propName, props}) {
const value = props[propName]; // Analyzable
return <div>{value}</div>;
}
// ✅ Use standard Math methods
function Component() {
return <div>{Math.sin(Math.PI / 2)}</div>;
}
故障排查
我需要计算动态代码
你可能需要计算用户提供的代码:
-
js
// ❌ Wrong: eval in component
function Calculator({expression}) {
const result = eval(expression); // Unsafe and unoptimizable
return <div>Result: {result}</div>;
}
改为使用安全的表达式解析器:
js
// ✅ Better: Use a safe parser
import {evaluate} from 'mathjs'; // or similar library
function Calculator({expression}) {
const [result, setResult] = useState(null);
const calculate = () => {
try {
// Safe mathematical expression evaluation
setResult(evaluate(expression));
} catch (error) {
setResult('Invalid expression');
}
};
return (
<div>
<button onClick={calculate}>Calculate</button>
{result && <div>Result: {result}</div>}
</div>
);
}
注意:
切勿将
eval与用户输入一起使用——这是安全风险。针对特定用例使用专门的解析库,如数学表达式、JSON 解析或模板计算。
帮助我们改进文档
发现翻译问题或内容错误?请告诉我们。
