我尝试使用reactJS动态构建一个表,但有两个我无法解决的问题:
<GridRow data={data1} key={i} />
我真的不想获取“全局”var,而是使用发送到方法的数据?我该怎么做?Error while rendering "GridBox" to "react1": Unable to get property 'data' of undefined or null reference
代码
var data1 = {"Columns":[{"Title":"Title1","HTMLClass":"g1_Title"},{"Title":"Title2","HTMLClass":"g2_Title"},{"Title":"Title3","HTMLClass":"g3_Title"}],"Rows":[{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]},{"Cells":["Cell0","Cell1","Cell2"]}]};
var GridRow = React.createClass({
render: function() {
if(this.props.data){
var Cell = this.props.data.Columns.map(function (column, i) {
return (
<div className={column.HTMLClass}>{this.props.data.Cells[i]}</div>
);
})
}
return (
<li>{Cell}</li>
);
}
});
var GridHead = React.createClass({
render: function() {
if(this.props.data){
var Cell = this.props.data.Title;
var HtmlClass = this.props.data.HTMLClass;
}
return (
<div className={HtmlClass}>{Cell}</div>
);
}
});
var GridList = React.createClass({
render: function() {
if(this.props.data){
var Header = this.props.data.Columns.map(function (columns) {
return (
<GridHead data={columns} />
);
});
var Row = this.props.data.Rows.map(function (data, i) {
return (
<GridRow data={data1} key={i} />
);
});
}
return (
<ul>
<li>{Header}</li>
{Row}
</ul>
);
}
});
var GridBox = React.createClass({
render: function(){
return (
<GridList data={data1} />
);
}
});
答案 0 :(得分:2)
您只能引用传递给map中函数的内容,除非您使用bind来维护this
的实例,以便它在组件和map中使用的函数中是相同的。这样您就可以在映射函数中使用this.props
。
由于header
正在使用直接传递给map
中的函数的内容,因此不一定需要绑定。在row
中,为了访问this.props
,必须绑定该函数。例如,如果您想somedata
访问this.props
:
var header = this.props.data.Columns.map(function (columns) {
return (
<GridHead data={columns} />
);
});
var Row = this.props.data.Rows.map(function (data, i) {
return (
<GridRow data={this.props.somedata} key={i} />
);
}.bind(this));
请注意,在JSX中,常规变量名称应以小写字母开头(如上图所示),而组件名称应以大写字母开头。