已设置window.React = React仍触发react/react-in-jsx-scope报错的技术求助
Let's break down why you're hitting this error and walk through the straightforward fixes:
The Root Cause
The ESLint rule react/react-in-jsx-scope requires every file that uses JSX to have React imported into its local scope. Even though you've imported React in index.js, your Menu.js component is a separate module with its own isolated scope—so React isn't automatically available there unless you explicitly add the import.
Before React 17, JSX gets compiled to React.createElement() calls under the hood, which depends on React being in scope to run. That's exactly why this rule exists!
Fix 1: Add React Import to Your Menu Component
This works for any React version, and it's the most universal fix. Just add the React import at the top of your Menu.js file:
// Menu.js import React from 'react'; function Menu({ recipes }) { // Your component's JSX logic here return ( <div className="menu-container"> {recipes.map(recipe => ( <div key={recipe.id} className="recipe-item"> <h2>{recipe.name}</h2> <p>{recipe.description}</p> </div> ))} </div> ); } export default Menu;
Fix 2: Disable the Rule (For React 17+)
If you're using React 17 or newer, the JSX transform was updated to remove the need for importing React in every JSX file. You can safely turn off this ESLint rule:
- Create or open your project's
.eslintrc.jsonfile in the root directory, then add:
{ "extends": "react-app", "rules": { "react/react-in-jsx-scope": "off" } }
- Alternatively, if you keep ESLint config in
package.json, add this to theeslintConfigsection:
"eslintConfig": { "extends": "react-app", "rules": { "react/react-in-jsx-scope": "off" } }
Restart your development server after making either change to apply the ESLint updates.
内容的提问来源于stack exchange,提问作者toshi

