我正在尝试使用 React JSX 在 Gatsby 中创建条件渲染。我为该函数提供了一些参数,如下所示:
const Button = (href, text, btnType, ...props) => {
if (href.contains("http")) {
return (
<a href={href} {...props}>
<button className={btnType}>
<span>{text}</span>
</button>
</a>
)
} else {
return (
<Link to={href} {...props}>
<button className={btnType}>
<span>{text}</span>
</button>
</Link>
)
}
}
如您所见,该函数的几个参数是 href、text 和 btnType。
在我实现Button组件的页面上,如下:
<Button
btnType="btn-cta"
text="External Link"
href="https://google.com">
</Button>
<Button
btnType="btn-nav"
text="Internal Link"
href="/">
</Button>
但它提供了TypeError: href.contains is not a function
错误。
我可以做什么来解决这个问题?我对 JavaScript 和 React 非常陌生,所以任何详细的答案将不胜感激,这样我就可以完全理解我的代码出了什么问题。
最佳答案
href
是组件的 Prop 。不是参数。您需要使用
const Button = ({ href, text, btnType, ...props }) => {...
这意味着您想要 destructure函数的第一个参数,并从 props 对象中获取 href
、text
、btnType
,然后获取 rest 将 props 放入 ...props
中。
根据您当前的代码,href
参数包含组件的所有 属性,而不仅仅是 href
属性。在 Button
函数中放置一个断点,您将看到 href
是一个对象。
此外,如@George在他们的comment中提到,您应该使用 includes
,因为 contains
已被弃用,并且现代浏览器中的 String 原型(prototype)上可能不存在。
关于javascript - TypeError : xxx.包含不是React中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58256469/