2014-11-05 70 views
13

我有,我有,有一個必需的「src」屬性和一個可選的「鏈接」屬性,它看起來像這樣一個圖像組件的使用情況:在選擇性地再現可選組件的屬性作出反應JSX

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」是可以或可以不包含一個稱爲屬性的對象的示例「值「,其中包括要點擊圖像時要瀏覽到的超鏈接。另外,如果沒有link.value存在,我寧願將它完全拋棄,而不是簡單地將空字符串作爲「鏈接」屬性的值。

我的推理是,在Image組件上,我只能在img實際鏈接到某處時添加css「img:hover {cursor:pointer;}」,而不是全局設置它,這違反了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 
} 

想象如何失控的,如果你有很多的,將得到可選的道具,你想離開...

回答

22

你似乎正在超越它。

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

在你的組件中,你通常應該忽略任何falsy值。

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

一個例外是數字,或罕見的(和最好的避免的情況下),它是布爾默認爲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} />