如何将this
带入我的.map()
循环?它似乎消失了。 : - (
我正在制作一个动态表格"用户可以为其表单指定多行输入。我想迭代state.items[]
中的所有项目并为它们构建表单输入字段。
例如,表格以'字段'开头。和' 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 );
答案 0 :(得分:13)
在.map
中未引用您的组件。有多种方法可以解决此问题
将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>
);
}
为this
回调设置.map
(,如果您无法使用ES2015
功能,则首选此变体)
this.state.items.map(function (object, i) {
// ....
}, this);
使用arrow function
this.state.items.map((object, i) => {
// ....
})
使用.bind
this.state.items.map(function(object, i) {
// ....
}.bind(this))
答案 1 :(得分:0)
map
和filter
等迭代方法的第二个参数是this
对象
所以你可以按如下方式使用它:
this.state.items.map(yourfunction,this)
答案 2 :(得分:0)
调用函数时。这是设置为全局对象,除非它是您正在调用的成员方法,或者您使用.call
或.apply
进行调用,而不是您的情况。
或者换句话说,你不能关闭this
,但是你可以更接近你为此分配的标准变量。所以一般来说,如果你有一个嵌套在另一个函数中的函数,你希望参考这个:
function outer(){
var _this = this;
someThingThatAcceptsACallback(function(){
console.log(_this.state);
}
}
答案 3 :(得分:0)
如果您正在使用Babel或其他现代EcmaScript6-&gt; JS5编译器,则可以使用更简单的语法来保留外部上下文的上下文:
{
this.state.items.map((object, i) => {
return ( <div>
<strong> State.autocomplete_from:
{this.state.autocomplete_from}
</strong>
/*.... your code ...*/ </div>);
});
}
通过使用箭头函数语法,this
上下文自动绑定在包含的函数中,因此您可以使用this
,因为您不需要在您的任何内容中执行任何特殊操作代码。