我试图弄清楚如何在状态组件中使用 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/