gpt4 book ai didi

javascript - 有条件地与react-router链接链接

转载 作者:行者123 更新时间:2023-12-03 13:33:59 24 4
gpt4 key购买 nike

我的 React 组件中有一种情况:我希望将一些元素包装在 Link 中组件如果 this.props.isComingFromModal是假的。

我做了什么(JSX):

<If condition={!this.props.isComingFromModal}>
<Link
to={{ pathname: `vendors/${benefit.vendor.id}`, state: { modal: false } }}
>
<img
className="Benefit__vendor__thumb"
src={benefit.vendor.tinyLogoUrl}
alt="Ponto Frio"
/>


<div className="Benefit__vendor__info">
<h2 className="Benefit__vendor__title">{benefit.vendor.tradingName}</h2>
<div className="rating">
<Rating
readonly
initialRate={benefit.vendor.rating}
className="rating"
fractions={2}
empty="icon-rating icon-rating--empty fa fa-star fa-2x"
full="icon-rating fa fa-star fa-2x"
/>
</div>
</div>
</Link>
<Else />
<img
className="Benefit__vendor__thumb"
src={benefit.vendor.tinyLogoUrl}
alt="Ponto Frio"
/>


<div className="Benefit__vendor__info">
<h2 className="Benefit__vendor__title">{benefit.vendor.tradingName}</h2>
<div className="rating">
<Rating
readonly
initialRate={benefit.vendor.rating}
className="rating"
fractions={2}
empty="icon-rating icon-rating--empty fa fa-star fa-2x"
full="icon-rating fa fa-star fa-2x"
/>
</div>
</div>
</If>

但我认为这有点重复。我不能做类似 (JSX) 的事情

<Link
to={{ pathname: `vendors/${benefit.vendor.id}`, state: { modal: false } }}
condition={!this.props.isComingFromModal}
>
<img
className="Benefit__vendor__thumb"
src={benefit.vendor.tinyLogoUrl}
alt="Ponto Frio"
/>


<div className="Benefit__vendor__info">
<h2 className="Benefit__vendor__title">{benefit.vendor.tradingName}</h2>
<div className="rating">
<Rating
readonly
initialRate={benefit.vendor.rating}
className="rating"
fractions={2}
empty="icon-rating icon-rating--empty fa fa-star fa-2x"
full="icon-rating fa fa-star fa-2x"
/>
</div>
</div>
</Link>

在这个假设的场景中,我将展示链接组件,只要 this.props.isComingFromModal 。有办法做到这一点吗?

最佳答案

我的简单功能解决方案:

import React from 'react'
import { Link } from 'react-router-dom'

export default function ConditionalLink({ children, condition, ...props }) {
return !!condition && props.to ? <Link {...props}>{children}</Link> : <>{children}</>
}

然后你可以像这样使用它:

<ConditionalLink to="/path" condition={!isComingFromModal}>
conditional link
</ConditionalLink>

关于javascript - 有条件地与react-router链接链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com