gpt4 book ai didi

reactjs - 在 React JSX 中选择性地渲染可选组件属性

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

我有一个用例,其中有一个图像组件,该组件具有必需的“src”属性和可选的“link”属性,如下所示:

var Image = React.createClass({

propTypes: {
link: React.PropTypes.string,
event: React.PropTypes.object,
src: React.PropTypes.string.isRequired
},

handleClick: function(event, link) {
analytics.track(event)
.then(function() {
window.location = link;
});
},

render: function() {
return (
<img className='image' src={this.props.src} onClick={this.handleClick.bind(this, this.props.event, this.props.link)} />
);
} });

如果我想在调用图像组件时有选择地包含可选 Prop ,我该如何优雅地做到这一点?我最初的想法是做一个像这样的三元表达式,除了这不是有效的 JSX:

render: function() {
return (
<Image src={this.props.src} {this.props.link.hasOwnProperty('value') ? link=this.props.link.value : ''} />
)
}

在上面的示例中,“this.props.link”是一个对象,可能包含也可能不包含名为“value”的属性,其中包含单击图像时要浏览到的超链接。另外,如果不存在 link.value,我宁愿将其完全忽略,而不是简单地提供一个空字符串作为“link”属性的值。

我这样做的原因是,只有当 img 实际上链接到某个地方时,我才能在 Image 组件上添加 css“img:hover {cursor:pointer;}”,而不是全局设置它,这违反了我的 UX 规则应用程序。

我知道我可以简单地在三元组中渲染“link”属性,其中包含链接的值(如果存在),如果不存在则为空字符串,但出于好奇,我想看看是否存在也许是实现这一目标的另一种方式。

我还希望避免执行一堆创建大量冗余 JSX 代码的条件语句,如下所示:

render: function() {
if (this.props.link.hasOwnProperty('value')) {
return <Image link={this.props.link.value} src={this.props.src.value} />;
} else {
return <Image src={this.props.src.value} />;
}
.... // other optional properties
}

想象一下,如果你有很多可选的 Prop 想要放弃,那会变得多么失控......

最佳答案

看来你想多了。

<Image src={this.props.src} link={this.props.link.value} />

在您的组件中,您通常应该将任何虚假值视为省略。

if (this.props.link) {
...
}

数字是一个异常(exception),或者是罕见的(最好避免的情况),其中 bool 值默认为 true。

<小时/>

更直接的答案是使用点差(0.12 中的新功能)。

var props = {src: this.props.src};
if (this.props.link.hasOwnProperty('value')) {
props.link = this.props.link.value;
}

<Image {...props} />

var extraProps = {};
if (this.props.link.hasOwnProperty('value')) {
extraProps.link = this.props.link.value;
}

<Image src={this.props.src} {...extraProps} />

关于reactjs - 在 React JSX 中选择性地渲染可选组件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26769387/

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