如何创建ESLint规则要求表单内React组件必须带指定Prop?
配置ESLint实现表单内组件强制指定属性的要求
要实现这个场景化校验需求,你需要编写自定义ESLint规则——因为内置规则无法区分组件所在的父容器场景。具体步骤如下:
1. 编写自定义ESLint规则
在项目中创建自定义规则文件,比如 eslint-rules/require-someprop-in-form.js,代码逻辑如下:
module.exports = { meta: { type: "problem", docs: { description: "要求form内的CustomButton必须指定someProp属性", category: "Best Practices", recommended: true }, fixable: null, schema: [] }, create(context) { return { // 匹配JSX中的CustomButton组件 JSXOpeningElement(node) { if (node.name.name !== 'CustomButton') return; // 向上遍历祖先节点,检查是否处于form标签内 let parent = node.parent; let isInsideForm = false; while (parent) { if (parent.type === 'JSXOpeningElement' && parent.name.name === 'form') { isInsideForm = true; break; } parent = parent.parent; } if (!isInsideForm) return; // 检查组件是否携带someProp属性 const hasSomeProp = node.attributes.some(attr => attr.type === 'JSXAttribute' && attr.name.name === 'someProp' ); if (!hasSomeProp) { context.report({ node, message: '表单内的CustomButton必须指定someProp属性' }); } } }; } };
2. 在ESLint配置中引入并启用规则
修改项目的ESLint配置文件(比如 .eslintrc.js),添加自定义规则的引用并启用:
module.exports = { // 其他原有配置... rules: { // 其他原有规则... "./eslint-rules/require-someprop-in-form": "error" } };
3. 验证规则效果
按照你给出的示例代码测试:
div容器内的CustomButton无论是否带someProp都不会触发报错form容器内的CustomButton如果未指定someProp,ESLint会直接抛出错误提示
内容的提问来源于stack exchange,提问作者cobbdb
相关产品推荐
相关产品推荐

