javascript - ReactJS - 如果对象有长度

标签 javascript reactjs

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

我尝试使用的“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>
        );
    }
}

最佳答案

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

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>
        );
    }

关于javascript - ReactJS - 如果对象有长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46859574/

相关文章:

java - 从 Google 应用引擎提供 dart Web 应用程序

javascript - 当轮播到达最后一张时返回第一张幻灯片

javascript - 尝试用圆圈创建图案?

javascript - 是否可以在一个 react ​​组件中有两种状态

javascript - 适合移动设备的 Airbnb react 日期库的配置

reactjs - 如何在 react-quill 中注册对齐样式

javascript - 按值传递而不是引用 JavaScript 闭包 - 任何非包装技术?

javascript - Angular 应用程序中的 Angular 应用程序是否可能?

css - 来自 css 样式表的 React 类样式不起作用

reactjs - React-native 在重新加载时改变样式