我正在创建一个<table>
带有React 0.14.6
的列标题,该列标题被动态插入到的<thead>
中<table>
:
CourseTable.js
:
import CourseList from './CourseList';
import GradesHeader from './GradesHeader';
import React, {Component} from 'react';
export default class CourseTable extends Component {
/**
* Gets all unique terms that have grades
* @param courses {Array}
* @return {Array}
*/
getUniqueTerms(courses) {
let uniqueTerms = [];
courses.forEach(course => {
if (course.grades) {
Object.keys(course.grades).forEach(term => {
if (uniqueTerms.indexOf(term) === -1) {
uniqueTerms.push(term);
}
})
}
});
return uniqueTerms;
}
createGradesHeaders(courses) {
return this.getUniqueTerms(courses).map(term => {
return (
<th>
<GradesHeader headerText={term}/>
</th>
);
});
}
render() {
let headers = this.createGradesHeaders(this.props.courses);
return (
<table className="table table-bordered table-condensed">
<thead>
<tr>
<th>
Period
</th>
<th>
Class
</th>
<th>
Term
</th>
<th>
Date Enrolled
</th>
<th>
Date Left
</th>
<th>
<div>Absenses</div>
<div>All (Excused)</div>
</th>
<th>
Tardies
</th>
<th></th>
{headers}
<th>
Teacher
</th>
</tr>
</thead>
<CourseList courseData={this.props.courses}/>
</table>
);
}
}
GradesHeader.js
:
import React, {Component} from 'react';
export default class GradesHeader extends Component {
render() {
return (
<div>
{this.props.headerText}
</div>
);
}
}
Course.js
:
import React, {Component} from 'react';
export default class Course extends Component {
render() {
const unexcused = !!this.props.courseData.attendance.unexcused ? this.props.courseData.attendance.unexcused : 0;
const excused = !!this.props.courseData.attendance.excused ? this.props.courseData.attendance.excused : 0;
const totalAbsences = unexcused + excused;
return (
<tr>
<td>
{this.props.courseData.expression}
</td>
<td>
{this.props.courseData.course_name}
</td>
<td>
{this.props.courseData.abbreviation}
</td>
<td>
{this.props.courseData.dateenrolled}
</td>
<td>
{this.props.courseData.dateleft}
</td>
<td>
{totalAbsences}
({excused})
</td>
// Grades for this course go here
<td>
</td>
<td>
{this.props.courseData.lastfirst}
</td>
</tr>
);
}
}
您可以在CourseTable.js
哪里动态地生成表的此部分的标题<thead>
。我对如何将每个年级的数据插入/插入相应的列感到困惑。
我认为我需要以某种方式标识<th>
动态生成的每个标头元素,并在插入这些列时引用它们,但是我不确定如何。
如评论中所述,您应该使用状态。状态非常有用。ReactJS指出,如果您想添加新的标头,可以为其分配一个ID,以便在呈现新标头时可以正确地循环浏览它们。如前所述,应对状态变化做出反应。在facebook教程页面和文档中都有一些示例。
假设您将所有标头收集在一个对象中,或者它们可能来自数据库。
var headers = [{id: 0, name: grade}
{id: 1, name: term}
]
因此,在head的render方法中,您可以像这样放置它们:
constructor(props) {
super(props);
this.state = {
headers: headers,
}
},
sortAlg(arr) {
//Choose one, make one
},
render() {
this.sortAlg(this.state.headers);
var headerArr = [];
headers.forEach(function(header) {
headerArr.push(<YourHeader header = {header} />
});
return (
<table className="table table-bordered table-condensed">
<thead>
{headerArr}
</thead>
<CourseList courseData={this.props.courses}/>
</table>
);
该<YourHeader />
是你做出更好的控制的组件。我至少喜欢这样。
希望对您有帮助,祝您好运。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句