简体   繁体   中英

Inherit props from parent functional component in React.js

In a functional component I want to access props inherited from the parent functional component. To get an idea what I mean, I have the following snippet:

function MainApp(props) {
    const { classes } = props;
    const [content, setContent] = useState("");

    return (
        <div className={classes.root}>
            <AppBar position="fixed" className={classes.appBar}>
                <Toolbar className={classes.toolbar}>
                    <Typography variant="title" color="inherit" fontWeight="bold">
                        CashCo
                    </Typography>
                    <ToolbarActions className={classes.toolbarActions} />
                </Toolbar>
            </AppBar>
            <main className={classes.appContent}>
                <PageContent content={content} />
            </main>
        </div>
    );
}

function App(props) {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<MainApp />}></Route>
            </Routes>
        </BrowserRouter>
    );
}

I want to pass the props argument in the App() function to the MainApp(), such that I don't have to access properties like props.props.some_property . How can I do that correctly? Cause passing props like this <MainApp props={props} /> means I have to access the properties like props.props.some_property in MainApp(), that's not what I want. I want to access the props like props.some_property in MainApp().

You can spread the App props onto MainApp , this will let you access them like so props.classes .

function App(props) {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<MainApp {...props} />}></Route>
            </Routes>
        </BrowserRouter>
    );
}

Try like this

function App(props) {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<MainApp {...props}/>}></Route>
            </Routes>
        </BrowserRouter>
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM