gpt4 book ai didi

javascript - 我如何有条件地在 React 中的某些 HTML 中间包含标签

转载 作者:行者123 更新时间:2023-11-29 10:13:54 26 4
gpt4 key购买 nike

我有一个 Avatar React 组件,可以选择是否链接到个人资料。你可能不希望它链接到一个配置文件,比如说,你在用户配置文件上,而是想做一个自定义的 clickHandler。除了链接之外,除了在每个 if 和 else 中使用基本相同的 HTML 执行 if/else 之外,还有更好的方法吗?下面是一些伪渲染代码,只是为了说明我的意思:

 <div className={"Avatar Avatar--" + this.props.size} onClick={this.props.clickHandler}>
{if (this.props.link) {
<Link to="profile" params={{userId:this.props.user.id}}>
}
}

<img className="__avatarimage" src={this.props.user.avatar} />

{if (this.props.link) {
</Link>
}
}
</div>

最佳答案

使用:

<div className={"Avatar Avatar--" + this.props.size} onClick={this.props.clickHandler}>
{ this.props.link ?
<Link to="profile" params={{userId:this.props.user.id}}>
<img className="__avatarimage" src={this.props.user.avatar} />
</Link>
: <img className="__avatarimage" src={this.props.user.avatar} /> }

您可以尝试通过更早地定义 img 来消除它的双重定义:

var img = <img className="__avatarimage" src={this.props.user.avatar} />;

并使用以下方式嵌入它:

{img}

关于javascript - 我如何有条件地在 React 中的某些 HTML 中间包含标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27032630/

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