仅当定义了 prop 时才显示 <div>
Show <div> only if prop is defined
我只想显示已定义的 React 组件的图标。
这是我的代码:
export const Button = ({ children, link, icon, background }) => {
return (
<Link href={`${link}`} passHref>
<button
className={`mt-4 inline-flex px-5 py-3 rounded-xl text-base font-medium text-white ${background} hover:bg-indigo-800 active:bg-grey-900 focus:outline-none border-4 border-white focus:border-purple-200 transition-all`}
>
{children}
{this.props.icon ? <Icon path={`${icon}`} /> : null}
</button>
</Link>
);
};
但是当我 运行 它时,我得到一个 'TypeError: Cannot read 属性 'props' of undefined'
知道如何解决吗?
什么是this.props
?您的函数参数在函数签名中被解构为局部变量:
export const Button = ({ children, link, icon, background }) => {
并且您已经使用了那些局部变量,包括此处的 icon
:
<Icon path={`${icon}`} />
因此您可以完全按照已经使用它和其他变量的方式使用它:
{icon ? <Icon path={`${icon}`} /> : null}
你已经解构了道具所以没必要this.props.icon
只用icon
因为您使用的是 React 功能组件 this.props 是无关紧要的。
这个 用于 Class 个组件。如果你想学习more
export const Button = ({ children, link, icon, background }) => {
这个 Button 是一个箭头函数(另一种声明函数的方式),它接受 props 作为参数,但是你在这里解构了 props,所以你不必使用 props.link,props.children等
我只想显示已定义的 React 组件的图标。 这是我的代码:
export const Button = ({ children, link, icon, background }) => {
return (
<Link href={`${link}`} passHref>
<button
className={`mt-4 inline-flex px-5 py-3 rounded-xl text-base font-medium text-white ${background} hover:bg-indigo-800 active:bg-grey-900 focus:outline-none border-4 border-white focus:border-purple-200 transition-all`}
>
{children}
{this.props.icon ? <Icon path={`${icon}`} /> : null}
</button>
</Link>
);
};
但是当我 运行 它时,我得到一个 'TypeError: Cannot read 属性 'props' of undefined' 知道如何解决吗?
什么是this.props
?您的函数参数在函数签名中被解构为局部变量:
export const Button = ({ children, link, icon, background }) => {
并且您已经使用了那些局部变量,包括此处的 icon
:
<Icon path={`${icon}`} />
因此您可以完全按照已经使用它和其他变量的方式使用它:
{icon ? <Icon path={`${icon}`} /> : null}
你已经解构了道具所以没必要this.props.icon
只用icon
因为您使用的是 React 功能组件 this.props 是无关紧要的。 这个 用于 Class 个组件。如果你想学习more
export const Button = ({ children, link, icon, background }) => {
这个 Button 是一个箭头函数(另一种声明函数的方式),它接受 props 作为参数,但是你在这里解构了 props,所以你不必使用 props.link,props.children等