ReactJS - 如果对象有长度

时间:2017-10-21 02:45:30

标签: javascript reactjs

我正在试图找出如何在我的状态组件中使用if语句来确定是否应该根据对象是否具有值来显示元素。逻辑是否应存在于单独的道具组件中?

我试图使用的“If语句”:

if(props.files){
  return ( <button className={ this.state.fileLinksButtonClosed ? "record-footer__accordion-button record-footer__file-links-button--closed" : "record-footer__accordion-button record-footer__file-links-button--opened"} onClick={this.handleClick}>File Attachments ({this.props.files.length})</button>
} else {
  return null;
}

当前组件:

//Record - Footer - File Link Accordion
class RecordFilesAccordion extends React.Component {
    constructor(props){
        super(props);
        this.state = { 
            fileLinksHidden: true,
            fileLinksButtonClosed: true
        };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(){
        this.setState({ 
            fileLinksHidden: !this.state.fileLinksHidden,
            fileLinksButtonClosed: !this.state.fileLinksButtonClosed
        });
    }

    render() {
        return (
            <div className="annotation-file">
                <button className={ this.state.fileLinksButtonClosed ? "record-footer__accordion-button record-footer__file-links-button--closed" : "record-footer__accordion-button record-footer__file-links-button--opened"} onClick={this.handleClick}>File Attachments ({this.props.files.length})</button>
                { this.state.fileLinksHidden ? null : <RecordFiles files={this.props.files}/> }
            </div>
        );
    }
}

1 个答案:

答案 0 :(得分:6)

如果要检查对象是否有任何值或为空,可以使用

if(Object.keys(props.files).length>0)

作为条件。如果props.files是一个至少有1个元素的数组,或者是一个至少有1个字段的对象,那么这将是true

编辑(在@cphill发表评论后):我认为你的渲染方法应该是

 render() {
        return (
            <div className="annotation-file">
               {Object.keys(props.files).length>0?
                <button className={ this.state.fileLinksButtonClosed ? "record-footer__accordion-button record-footer__file-links-button--closed" : "record-footer__accordion-button record-footer__file-links-button--opened"} onClick={this.handleClick}>File Attachments ({this.props.files.length})</button>
                : null}
                { this.state.fileLinksHidden ? null : <RecordFiles files={this.props.files}/> }
            </div>
        );
    }