[英]How do I conditionally include a tag in the middle of some HTML in React
I have an Avatar
React component and there's an option to make it link to a profile or not. 我有一个
Avatar
React组件,可以选择是否链接到个人资料。 You may not want it to link to a profile if, say, your on the users profile and instead you want to do a custom clickHandler
. 您可能不希望它链接到配置文件,例如,如果您在用户配置文件上,而是您想要执行自定义
clickHandler
。 Is there a nicer way other than just doing an if/else with basically identical HTML in each if and else other than a link? 有没有更好的方法,除了在每个if和else链接之外只使用基本相同的HTML进行if / else? Below is some pseudo rendering code just to show an example of what I mean:
下面是一些伪渲染代码,只是为了展示我的意思:
<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>
Use: 使用:
<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} /> }
You can try to eliminate double definition of img by defining it earlier: 您可以尝试通过先前定义img来消除img的双重定义:
var img = <img className="__avatarimage" src={this.props.user.avatar} />;
and embed it using: 并使用以下方法嵌入:
{img}
I'd create a function that either returns the image or the image wrapped in the link and then add it to the div. 我创建了一个函数,它返回图像或链接中包含的图像,然后将其添加到div。
var createAvatar = function() {
if (this.props.link) {
return <Link to="profile" params={{userId:this.props.user.id}}>
<img className="__avatarimage" src={this.props.user.avatar} />
</Link>;
} else {
return <img className="__avatarimage" src={this.props.user.avatar} />;
}
};
var avatar = createAvatar();
return <div className={"Avatar Avatar--" + this.props.size} onClick={this.props.clickHandler}>
{avatar}
</div>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.