【问题标题】:Selectively rendering optional component properties in React JSX在 React JSX 中选择性地呈现可选组件属性
【发布时间】:2014-11-05 23:53:06
【问题描述】:

我有一个用例,其中我有一个 Image 组件,它有一个必需的“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)} />
  );
} });

如果我想在调用 Image 组件时选择性地包含可选道具,我该如何优雅地做到这一点?我最初的想法是做一个像这样的三元表达式,除了这不是有效的 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 的情况下将其完全省略。

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

我知道我可以简单地将“链接”道具呈现在一个三元组中,如果它存在,则它包含链接的值,如果不存在,则为空字符串,但出于好奇,我想看看是否存在也许是另一种方式来实现这一点。

我还希望避免执行一堆创建大量冗余 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
}

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

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你好像想多了。

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

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

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

    一个例外是数字,或者是一个默认为 true 的布尔值的罕见(最好避免的情况)。


    更直接的答案是使用 spread(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} />
    

    【讨论】:

      猜你喜欢
      • 2021-01-05
      • 2021-05-22
      • 2019-06-28
      • 2016-01-02
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      相关资源
      最近更新 更多