我怎样才能携带this
进入我的.map()
环形?它似乎消失了。 :-(
我正在创建一个“动态表单”,用户可以在其中为其表单指定多行输入。我想迭代所有项目state.items[]
并为他们构建表单输入字段。
例如,表单以“field”和“autocomplete_from”开头。然后用户可以单击添加新行在他的表格中获得更多行。
102 render: function() {
103 return (
104 <div>
105 {this.state.items.map(function(object, i){
106 return (
107 <div>
109 <FieldName/>
110 <strong> State.autocomplete_from:
{this.state.autocomplete_from} </strong>
// ^^^
// Uncaught TypeError: Cannot read property 'state' of undefined
120 <button onClick={this.newFieldEntry}>Create a new field</button>
121 <button onClick={this.saveAndContinue}>Save and Continue</button>
122 </div>
123 );
124 })}
125 </div>
126 );
In .map
this不引用您的组件。有多种方法可以解决此问题
-
Save this
到变量
render: function() {
var _this = this;
return (
<div>
{this.state.items.map(function(object, i){
return (
<div>
<FieldName/>
<strong> State.autocomplete_from:
{_this.state.autocomplete_from} </strong>
<button onClick={this.newFieldEntry}>Create a new field</button>
<button onClick={this.saveAndContinue}>Save and Continue</button>
</div>
);
})}
</div>
);
}
-
Set this
for .map
打回来(如果你不能使用ES2015
功能,此变体是首选)
this.state.items.map(function (object, i) {
// ....
}, this);
-
use arrow function
this.state.items.map((object, i) => {
// ....
})
-
use .bind
this.state.items.map(function(object, i) {
// ....
}.bind(this))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)