我想在courses数组为空时隐藏表元素。我希望下面的代码可行,但事实并非如此。有任何想法吗?有问题的代码行是:
<table className="table" style={courses.length > 0 ? 'show' : 'display:none'}>
import React, {PropTypes} from 'react';
import CourseListRow from './CourseListRow';
const CourseList = ({courses, onDelete}) => {
return (
<table className="table" style={courses.length > 0 ? 'show' : 'display:none'}>
<thead>
<tr>
<th> </th>
<th>Title</th>
<th>Author</th>
<th>Category</th>
<th>Length</th>
</tr>
</thead>
<tbody>
{courses.map(course =>
<CourseListRow key={course.id} course={course} onDelete={onDelete}/>
)}
</tbody>
</table>
);
};
CourseList.propTypes = {
courses: PropTypes.array.isRequired
};
export default CourseList;
答案 0 :(得分:3)
这里似乎没有必要应用动态类,但为什么不返回一个空元素(<span />
)而不是表本身呢?
const CourseList = ({courses, onDelete}) => {
if (courses.length === 0)
return <span />
}
return (
<table className="table">
...
</table>
);
};
这在React中是一种相当常见的方法,因为它允许从DOM中实际删除元素,而不是用CSS隐藏它们。
答案 1 :(得分:1)
<table className="table" style={courses.length > 0 ? 'display: '' : 'display:none'}>
这种语法完成了我最初要做的事情。也就是说,勒克斯的答案是一个更好的解决方案。所以我接受了。谢谢lux。