2015-10-19 31 views
5

我不想渲染冠軍時,說明空檢查反應元素爲空

var description = <MyElement />; // render will return nothing in render in some cases 

if (!description) { // this will not work because its an object (reactelement) 
    return null; 
} 

<div> 
    {title} 
    {description} 
</div> 

請告訴我,而不是正確的方法!能夠檢查其是否爲空?

+0

你有任何狀態/道具,你可以檢查看看_should_是否是空的?使用這些檢查更好,而不是檢查元素的孩子。 – J3Y

+0

不是真的,數據是通過在myelement組件中轉換/過濾的某些道具構建的。如果沒有辦法,我需要將此Logik移動到父組件。然後我可以檢查這個道具。 –

回答

1
var description, title; 

if (this.props.description) { 
    description = <Description description={this.props.description} />; 

    if (this.props.title) { 
     title = <Title title={this.props.title} />; 
    } 
} 

<div> 
    {title} 
    {description} 
</div> 

或者乾脆:

render() { 
    const { description, title } = this.props; 

    return (
    <div> 
     {title && description && <Title title={title} />} 
     {description && <Description description={description} />;} 
    </div> 
); 
} 

伊莫這是更好的做法是,如果不需要你的描述元素,則其不呈現,而不是返回空值在它的渲染。因爲你可能會通過道具發送數據。同樣,如果你不想渲染這個組件,那麼這應該發生在父級。

+1

所以唯一的解決方案是將元素中的數據轉換/過濾器​​的邏輯移入父級,然後檢查這個變量? Yup; –

+1

Yup;據我瞭解,這是React自上而下的渲染方案中非常有意的一部分。 – machineghost