React Context报错:Cannot find name 'SomeContext' ts(2304) 求助
问题:React Context 报错 "Cannot find name 'MathContext' ts(2304)"
核心原因
你在MathCard.tsx中定义了MathContext但未导出,子组件MathCardHeader.tsx无法访问该上下文对象,导致TypeScript抛出“找不到名称”的错误。此外代码还有两处逻辑问题需要修正。
分步解决方案
1. 导出并正确定义MathContext
修改MathCard.tsx,导出MathContext并指定匹配的类型(因为你需要传递num和setNum两个值):
import { useState, createContext, Dispatch, SetStateAction } from 'react' import MathCardHeader from './MathCardHeader' import MathCardBody from './MathCardBody' import MathCardFooter from './MathCardFooter' // 定义Context的类型结构 type MathContextType = { num: number; setNum: Dispatch<SetStateAction<number>>; } // 导出Context,初始值匹配类型要求 export const MathContext = createContext<MathContextType>({ num: 1, setNum: () => {} // 初始空函数避免渲染报错 }); const MathCard = () => { const [num, setNum] = useState(1); return ( <div className="card bg-dark-green text-white shadow-lg"> {/* 传递包含num和setNum的对象作为Context值 */} <MathContext.Provider value={{ num, setNum }}> <MathCardHeader /> <MathCardBody /> <MathCardFooter /> </MathContext.Provider> </div> ); }; export default MathCard;
2. 在子组件中导入MathContext
修改MathCardHeader.tsx,导入MathContext并修正输入值的类型转换:
import { useContext } from 'react' // 导入定义好的MathContext import { MathContext } from './MathCard' export default function MathCardHeader() { // 现在可以正确解构num和setNum const { num, setNum } = useContext(MathContext); return ( <div className="card-header bg-darker-green p-3"> <h2 className="display-5">Choose Your Number!</h2> <input value={num} onChange={(e) => { // 将输入的字符串转为数字,避免类型不匹配 setNum(Number(e.target.value)); }} className="form-control bg-dark-green text-white" type="number" placeholder="Enter your number" aria-label="Enter your number" /> <em>You have chosen number {num}.</em> </div> ); };
3. 其他注意事项
- 所有需要使用
MathContext的子组件(如MathCardBody、MathCardFooter)都需按同样方式导入MathContext - TypeScript会自动检查类型匹配,后续修改Context值结构时,类型定义会帮你提前发现错误
内容的提问来源于stack exchange,提问作者Craig Waton
相关产品推荐
相关产品推荐

