【问题标题】:Remove a prop from cloned React component从克隆的 React 组件中删除一个道具
【发布时间】:2019-01-18 19:32:00
【问题描述】:

目标:我需要对 React 组件进行一些后处理,这涉及到移除一些道具。我尝试使用React.cloneElement 传递{propToRemove: undefined} 作为第二个参数,但没有删除道具,只是设置为undefined。我可以使用React.createElement,但根据文档,这将失去refs,这是一个严重的缺点。

一个人为的例子,没有做任何有用的事情,只是为了测试:

const removeUnknownPropWithClone = (el) => {
  return React.cloneElement(el, {unknownProp: undefined})
};

const App = (props) => 
  removeUnknownPropWithClone(
    <div unknownProp="1">Hello</div>
  );

这显示了错误消息:“React 无法识别 DOM 元素上的 unknownProp 属性”。事实上,道具设置为undefined,但它仍然存在。我需要完全删除它。

Runnable snippet(打开控制台查看错误信息)

相关问题(但未在此处回答):React - Remove prop from child

相关源码:https://github.com/facebook/react/blob/master/packages/react/src/ReactElement.js#L293

【问题讨论】:

  • 查看stackoverflow.com/questions/43041013/…,看看能不能找到一些灵感?
  • 谢谢,@DamianSimonPeter,我做到了,甚至写了几个 cmets :)
  • 是的,我认为错误似乎有点简单,我可能错了。您不应该在 DOM 元素中包含“unknownProp=1”。我想这是你的错误的原因&lt;div unknownProp="1"@tokland
  • 是的,当然,这是一个人为的例子,我会在问题中添加一个注释。我希望处理删除正在其他地方使用的道具。

标签: javascript reactjs


【解决方案1】:

有时查看来源是件好事;)

cloneElement 不允许删除道具 - 它们被复制和覆盖。没有删除或传递函数的选项。

但是看高一点我们可以看到:

export function cloneAndReplaceKey(oldElement, newKey) {
  const newElement = ReactElement(
    oldElement.type,
    newKey,
    oldElement.ref,
    oldElement._self,
    oldElement._source,
    oldElement._owner,
    oldElement.props,
  );

  return newElement;
}

看起来很容易扩展,但没有导出 ReactElement :]

...但看起来refkey 和修剪过的道具可以复制/传递(通过配置)到createElement。检查是否足够。

【讨论】:

【解决方案2】:

我们是这样解决的

const { propToRemove, ...childProps } = child.props
const filteredChild = { ...child, props: childProps }

return React.cloneElement(filteredChild, additionalProps)

【讨论】:

    【解决方案3】:

    使用 JSX 非常简单(在 Children.map() 函数中):

    const { filtered, ...rest } = child.props
    const clone = <child.type key={child.key} ref={child.ref} {...rest} />
    
    

    【讨论】:

      【解决方案4】:

      您可以将元素道具复制到另一个对象并删除新对象中不需要的道具

      const removeUnknownPropWithClone = (el) => {
        const props = { ...el.props }
        delete props['unknownProps']
        return React.cloneElement(el, props)
      };
      

      【讨论】:

      • 传递给 cloneElement 的道具被合并到 el.props 中,所以unknownProp 仍然存在。
      猜你喜欢
      • 2021-01-25
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 2012-01-11
      相关资源
      最近更新 更多