将 react-router-dom Link 组件作为渲染道具传递失败

Passing react-router-dom Link component as a render prop is failing

我正在尝试将 react-router-dom Link 组件作为渲染道具传递给组件,但 运行 遇到了一些问题:

https://codesandbox.io/embed/xjm35923qo

我在将 <Link>hi</Link 作为渲染道具传递时收到的错误是 Invariant Violation Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

这似乎很公平,但如果我改为传入类似 () => <Link>hi</Link> 的内容,则不会出现错误,但会出现警告 (react-dom.development.js?7f13:507 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.) 而 link 不会t 渲染。

我无法理解这些错误消息 -- 我在这里遗漏了什么?

您应该将 Link 作为命名导入导入:

import {Link} from "react-router-dom"

并且您需要使用 Router 对象包装您的应用程序。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import