【问题标题】:Why do we have to specify the component prop differently than the other props in React Router DOM?为什么我们必须指定与 React Router DOM 中的其他 props 不同的组件 prop?
【发布时间】:2021-06-26 17:04:31
【问题描述】:

我们在使用render prop的时候,为什么要指定component prop为:

component: Component

所有其他道具都使用常规的解构语法:

exact

这是否特定于 React Router DOM,或者这通常是您在 React 中传递组件的方式?如果是这样,为什么我们必须使用这种语法?

【问题讨论】:

  • 您能否展示一个包含更多context 的示例?你在说reactrouter.com/web/api/Route/render-func吗?在这种情况下,{ component: Component, ...rest } 中的冒号是为了有效地 rename component 属性,参见例如stackoverflow.com/q/51959013/3001761.
  • 谢谢你,这就是我所指的功能。你知道我们为什么要重命名组件属性吗?
  • 因为它在 JSX 中使用。如果你把<component /> 解释为一个字符串,React.createElement("component"),而<Component /> 被解释为一个标识符React.createElement(Component)

标签: javascript reactjs react-router-dom


【解决方案1】:

我相信这里的原因是因为 React Router 较少用作父组件,而更多用作重定向库。将您的组件插入到 component 中会进行标准渲染,其中会注入查询字符串、历史记录和参数;然而,这不是唯一的选择。

<Route path={this.props.match.url} exact render={() => 
   <Admin location={this.props.location} history={this.props.history}/>
}/>

Route 的目的不是应用样式、道具或通用父属性,而是使用注入的道具和路径条件专门渲染子级。

【讨论】:

  • 谢谢,你知道我们为什么要重命名组件属性吗?
猜你喜欢
  • 2014-08-28
  • 2017-09-14
  • 2022-06-15
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-13
相关资源
最近更新 更多