【问题标题】:React, react.children + react.cloneElement breaks when using spread operatorReact,react.children + react.cloneElement 在使用扩展运算符时中断
【发布时间】:2017-03-20 12:40:13
【问题描述】:

我正在使用React.children 渲染一些带有反应路由器的子路由(对于某个主路由下的所有子路由。

这对我来说效果很好,但是我之前正在解构我传递给孩子们的道具 -

const { prop1, prop2, prop3 } = this.props;

 const children = React.Children.map(this.props.children, (child) => {
  return React.cloneElement(child, {
    prop1,
    prop2,
    prop3
  });
});

这一直很好,但是最近我开始获得更多的道具,所以我想我可以通过像这样将道具传播到子对象中来让它变得更容易:

 const children = React.Children.map(this.props.children, (child) => {
  return React.cloneElement(child, {...this.props});
})

这似乎没问题,但我现在出现了一些奇怪的行为,我无法再从 react 路由器看到我的 routeParams (this.props.routeParams)

似乎扩展运算符应该做同样的事情,只是代码更少,除非我误解了什么。

当我将其切换回非扩展运算符方法时,它可以正常工作。知道这是为什么吗?

【问题讨论】:

  • 我认为你不需要在这里使用 spread ,尝试按原样传递道具。 React.cloneElement(child, this.props);
  • @FabianSchultz 出现同样的问题,this.props.routeParams 由于某种原因没有更新:(

标签: javascript reactjs react-router


【解决方案1】:

React.Children.map 回调函数的第一个参数将设置回调的 this 上下文 (check the docs here)

当您将React.Children.map 回调的this 上下文作为第一个参数传递给回调时,您将其设置为值child

所以不是将 this.props 传递给 cloneElement,而是传递 child.props.routeParams

【讨论】:

  • 我认为胖箭头语法给了我这个之外,不是吗?
  • 不是当传入回调的参数用于定义this上下文时
  • 这是一个很好的发现,但我不确定它是否能解决问题。如果我确实喜欢 map 函数上方的 const props = this.props 然后在该 props 变量中传播,我仍然遇到同样的问题。也许反应路由器如何将其路由参数更新为道具的问题。
  • 也许发布该尝试的其余代码以及您的 React Router 设置的代码。您确定您的 props 包含地图之前的相关值?
猜你喜欢
  • 2020-04-06
  • 1970-01-01
  • 2019-08-10
  • 2020-07-08
  • 2016-06-12
  • 1970-01-01
  • 2018-12-09
  • 2018-06-25
  • 2022-12-10
相关资源
最近更新 更多