【发布时间】:2019-05-29 08:50:19
【问题描述】:
我是 ReactJS 的新手。 以下功能运行良好:
_renderTable: function() {
return(
React.DOM.table(null,
React.DOM.thead( {onClick: this._sort},
React.DOM.tr(null,
this.props.headers.map(function (title, idx) {
if (this.state.sortby === idx) {
title += this.state.descending ? ' \u2191' : ' \u2193'
}
return React.DOM.th({key: idx}, title);
}, this)
)
),
React.DOM.tbody( {onDoubleClick: this._showEditor},
this._renderSearch(),
this.state.data.map(function (row, rowidx) {
return(
React.DOM.tr({key: rowidx},
row.map(function (cell, idx) {
var content = cell;
//To-Do editable field on double click
var edit = this.state.edit;
if (edit && edit.row === rowidx && edit.cell === idx) {
content = React.DOM.form({onSubmit: this._save},
React.DOM.input({
type: "text",
defaultValue: content,
})
);
}
return React.DOM.td({
key: idx,
"data-row": rowidx
}, content);
}, this)
)
);
}, this)
)
)
);
},
当我使用 babel 重写它时:
_renderTable: function() {
return(
<table>
<thead onClick={this._sort}>
<tr>{
this.props.headers.map(function (title, idx) {
if (this.state.sortby === idx) {
title += this.state.descending ? ' \u2191' : ' \u2193'
}
return <th key={idx}>{title}</th>
}, this)
}</tr>
</thead>
<tbody onDoubleClick={this._showEditor}>
{this._renderSearch()}
{console.log("Hello", this.state)}
{
this.state.data.map(function (row, rowidx) {
return(
<tr key={rowidx}>{
row.map(function (cell, idx) {
var content = cell;
console.log("Hello2", this);
var edit = this.state.edit;
if (edit && edit.row === rowidx && edit.cell === idx) {
content = <form onSubmit={this._save}>
<input type="text" defaultValue={content}>
</input>
</form>
}
return <td key={idx}>{content}</td>
})
}</tr>
);
})
}
</tbody>
</table>
);
},
我收到以下错误:
Uncaught TypeError: Cannot read property 'state' of undefined
将var edit = this.state.edit; 替换为var edit = false; 可以消除错误。
搜索显示绑定this 在函数体中调用它的情况下,所以我尝试这样做但没有运气。不确定绑定中的问题,因为非 JSX 版本的代码工作正常。
【问题讨论】:
-
你的构造函数中是否有类似:
this._renderTable = this._renderTable.bind(this);? -
我有以下代码:
Excel = React.createClass({ ... getInitialState: function() { return { data: this.props.initialData, sortby: null, descending: false, edit: null, // {row: index, cell: index} search: false, }; },如果我尝试将 getInitialState 替换为构造函数,则会收到构造函数已创建的错误。
标签: javascript reactjs babeljs jsx