React包装器:React不识别DOM元素上的`staticContext` prop

Nic*_*art 22 reactjs react-router react-router-dom

我正在尝试围绕react-router-dom NavLink组件创建一个包装器组件.

我希望我的自定义组件接受所有NavLinks道具,并将它们代理到NavLink.

但是,当我这样做时,我得到:

__PRE__

可以在此处找到该问题的工作演示:https://codesandbox.io/s/w0n49rw7kw

谢谢,

Kho*_*hoa 37

有一种方法可以克服使用:

const { to, staticContext, ...rest } = this.props;
Run Code Online (Sandbox Code Playgroud)

所以你...rest永远不会包含staticContext


Has*_*alp 13

发生这种情况是因为您可能{...props}在组件中的某个地方使用了。

反应示例:

function MyDiv(props) {
  const { layout, ...rest } = props
  if (layout === 'horizontal') {
    return <div {...rest} style={getHorizontalStyle()} />
  } else {
    return <div {...rest} style={getVerticalStyle()} />
  }
}
Run Code Online (Sandbox Code Playgroud)

我们layout单独抓取,这样它就不会包含在{...rest}.


小智 7

这是一个简单的解决方案的常见问题,如React文档中所述

如果您尝试使用React无法识别为合法DOM属性/属性的道具来渲染DOM元素,则会触发unknown-prop警告。您应该确保您的DOM元素周围没有虚假的道具。

散布运算符可用于从props中提取变量,并将其余props放入变量中。

function MyDiv(props) {
  const { layout, ...rest } = props
  if (layout === 'horizontal') {
    return <div {...rest} style={getHorizontalStyle()} />
  } else {
    return <div {...rest} style={getVerticalStyle()} />
  }
}
Run Code Online (Sandbox Code Playgroud)

您还可以将道具分配给新对象,并从新对象中删除正在使用的键。确保不要从原始的this.props对象中删除props,因为该对象应该被认为是不可变的。

function MyDiv(props) {

  const divProps = Object.assign({}, props);
  delete divProps.layout;

  if (props.layout === 'horizontal') {
    return <div {...divProps} style={getHorizontalStyle()} />
  } else {
    return <div {...divProps} style={getVerticalStyle()} />
  }
}
Run Code Online (Sandbox Code Playgroud)