![](/img/trans.png)
[英]How can I conditionally include some Javascript in an html.slim file, as part of a larger Ruby on Rails project?
[英]How do I conditionally include a tag in the middle of some HTML in React
我有一个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来消除img的双重定义:
var img = <img className="__avatarimage" src={this.props.user.avatar} />;
并使用以下方法嵌入:
{img}
我创建了一个函数,它返回图像或链接中包含的图像,然后将其添加到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.