【问题标题】:Passing props from a parent component to a child component in react在反应中将道具从父组件传递给子组件
【发布时间】:2020-08-28 19:43:52
【问题描述】:

我正在尝试使用该行代码将属性从父组件传递给子组件:

const isPermitted = ["permitted","not-permitted"]

    const sideBar = [
        {
            id: 0, name: "Dashboard", icon: dashboard, path: `${url}/dashboard`, exact: true,
            component: () => <Dashboard isPermitted={isPermitted} />
        },

--编辑:这是我如何循环通过我的侧边栏数组来呈现我的路线:

{sideBar.map((route, index) => (
            <Route
                key={index}
                path={route.path}
                exact={route.exact}
                component={route.component} />
            ))}

这里的问题是,每当我转到仪表板组件并尝试控制台日志(道具)时,它总是显示一个空对象,而不是相应地显示包含其内容的数组。为什么会发生这种情况,我该如何解决?提前致谢。

【问题讨论】:

  • 为什么在这种情况下重复isPermitted isPermitted={isPermitted &amp;&amp; isPermitted}?应该是isPermitted={isPermitted}
  • @BoussadjraBrahim 我修复了它,但仍然无法正常工作。
  • 你是如何渲染那个组件的?我的意思是侧边栏
  • @BoussadjraBrahim 完成 :')
  • @BoussadjraBrahim 我正在使用功能组件。

标签: javascript reactjs react-props


【解决方案1】:

尝试使用render 属性而不是component

render: props => <Dashboard {...props} isPermitted={isPermitted} />

鉴于您的路线创建涉及map

{sideBar.map((route, index) => {
  const Component = route.component;

  return (
    <Route
      key={index}
      path={route.path}
      exact={route.exact}
      render={props => <Component {...props} isPermitted={isPermitted} />} />
  );
})}

【讨论】:

  • 我正在遍历我的侧边栏数组以使用组件属性呈现我的路线,所以我认为名称是组件还是渲染并不重要。
  • 如果您将每个组件作为其自己的组件传递给路由,它会这样做。 component 假定一个 prop-less 组件,而 render 让您可以更好地控制所呈现的内容。
  • 请你看看我是如何实现路由的!
  • 您可以将每个 route.component 视为 JSX 中的一个组件。我假设你不能在 JSX 中做&lt;route.component /&gt;,所以我先将它分配给一个变量。
  • 在侧边栏数组中尝试component:Dashboard
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 2018-07-21
  • 2020-11-23
  • 2021-01-16
相关资源
最近更新 更多