2015-10-19 37 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