【问题标题】:In how many ways we can pass props to all child components in react我们可以通过多少种方式将 props 传递给 react 中的所有子组件
【发布时间】:2021-12-09 18:18:52
【问题描述】:

我有一个应用代码

import React from "react";
import { Route, Switch } from "react-router-dom";
import Minidrawer from './components/Drawer/Minidrawer'
import { makeStyles } from '@mui/styles';
import Box from '@mui/material/Box';
import Main from "./components/Main/Main";
import {useSelector} from 'react-redux'


const useStyles = makeStyles({
  container: {
    display: "flex"
  }
});

export default function App() {
  const classes = useStyles();
  const user = useSelector((state) => state.auth);

  return (
    <Box sx={{ display: 'flex' }}>
      <Minidrawer currUser={user}/>
      <Switch>
        <Route exact from="/" render={props => <Main childText="home" currUser={user} {...props} />} />
        <Route exact path="/auth" render={props => <Main childText="auth" currUser={user} {...props} />} />
        <Route exact path="/register-client" render={props => <Main childText="registerClient" currUser={user} {...props} />} />
      </Switch>
      </Box>
  );
}

我必须将 currUser 传递给 App 中导入的所有子组件,但我不想复制代码,有什么不同的方法可以实现这一点,以便所有组件都可以访问 currUser?

【问题讨论】:

  • redux 或您在组件本身中调用的上下文变量
  • 组件可以随时调用的上下文变量
  • 你在每条路由中渲染同一个主组件,那你为什么不在主组件中调用useSelector而不是App呢?或者,映射路线请参阅:How Mapping Routes in React Router with Protected Function?

标签: javascript reactjs redux


【解决方案1】:

如果我理解你想要做什么,你想将 props 传递给组件的所有子组件,如果组件是简单组件,你可以这样做:

import React from "react";
import Main from "./Main";
import PassPropsToNormalComponents from "./PassPropsToNormalComponents";

export default function App() {
  const user = {
    username: "lakhdar"
  };

  return (
    <div style={{ display: "flex" }}>
      <PassPropsToNormalComponents currUser={user}>
        <Main childText="home" />
        <Main childText="auth" />
        <Main childText="registerClient" />
      </PassPropsToNormalComponents>
    </div>
  );

这是 PassPropsToNormalComponents 文件

import React from "react";

export default function PassPropsToNormalComponents({ children, ...props }) {
  const childrenWithProps = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { ...child.props, ...props });
    }
    return child;
  });

  return <>{childrenWithProps}</>;
}

但在您的情况下,将道具传递给路线不会让路线将道具传递给它们渲染的组件,因此我们需要在这里额外的步骤:

首先是我们向父级提供道具的文件:

import React from "react";
import { Route, Switch } from "react-router-dom";
import Main from "./Main";
import PassPropsToRouteComponents from "./PassPropsToRouteComponents";

export default function App() {
  const user = {
    username: "lakhdar"
  };

  return (
    <div style={{ display: "flex" }}>
      <Switch>
        <PassPropsToRouteComponents currUser={user}>
          <Route
            exact
            from="/"
            render={(props) => {
              return <Main childText="home" {...props} />;
            }}
          />
          <Route
            exact
            path="/auth"
            render={(props) => <Main childText="auth" {...props} />}
          />
          <Route
            exact
            path="/register-client"
            render={(props) => <Main childText="registerClient" {...props} />}
          />
        </PassPropsToRouteComponents>
      </Switch>
    </div>
  );
}

最后,额外的步骤是获取渲染元素并将它自己的 props + 来自父级的 props 传递给它,文件如下所示:

import React from "react";

export default function PassPropsToRouteComponents({ children, ...props }) {
  const childrenWithProps = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      const routerChild = child.props.render();
      return React.cloneElement(child, {
        ...child.props,
        render: () => {
          return React.cloneElement(routerChild, {
            ...routerChild.props,
            ...props
          });
        }
      });
    }
    return child;
  });

  return <>{childrenWithProps}</>;
}

工作代码框的链接:https://codesandbox.io/s/gracious-meadow-dj53s

我希望这是您一直在寻找的。​​p>

【讨论】:

    【解决方案2】:

    您可以使用 redux 或 context API。

    Redux:https://react-redux.js.org/

    上下文 API:https://reactjs.org/docs/context.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 2019-07-14
      • 2020-06-12
      • 1970-01-01
      相关资源
      最近更新 更多