React父组件传递的自定义props显示undefined的问题求助
问题根因
你传入的props为undefined是因为Main组件的入参写法错误:
- React函数组件的第一个参数才是所有外部传入属性+Redux注入属性的集合,第二个参数仅用于
forwardRef场景接收ref对象,你把isMainShown放到第二个参数中自然无法正常取值。
修复方案
方案1:直接从props对象取值
修改Main组件的入参和取值逻辑:
// 删除第二个参数,所有属性都从第一个props对象中获取 const Main = (props) => { console.log(props.isMainShown); useEffect(() => { props.ImportForamttedFile(); }, []); return ( <> {/* 从props中取isMainShown判断样式 */} <div className={props.isMainShown ? "mainPageActive" : "mainPage"}> {/* 其余路由代码保持不变 */} </div> </> ); };
方案2:入参直接解构(更简洁)
如果不想每次都写props.,可以直接在第一个入参位置解构所有需要的属性:
const Main = ({ isMainShown, Sheet, ImportForamttedFile }) => { console.log(isMainShown); useEffect(() => { ImportForamttedFile(); }, []); return ( <> <div className={isMainShown ? "mainPageActive" : "mainPage"}> <Switch> <Route exact path="/"> <Home /> </Route> <Route exact path="/GrossProfitView"> <GrossProfitView Sheet={Sheet} /> </Route> {/* 其余路由代码保持不变 */} </Switch> </div> </> ); };
额外优化提示
父组件WebHeader里的button标签使用了class属性,React规范中需要写成className,否则控制台会抛出属性不识别的警告。
内容的提问来源于stack exchange,提问作者MKaranjawala
相关产品推荐
相关产品推荐

