React:this.state在for循环中消失 [英] React: this.state disappears in for loop
问题描述
如何将此
带入我的 .map()
循环?它似乎消失了。 : - (
How can I carry this
into my .map()
loop? It seems to disappear. :-(
我正在创建一个动态表单,用户可以为其表单指定多行输入。我想迭代<$中的所有项目c $ c> state.items [] 并为它们构建表单输入字段。
I'm creating a "dynamic form" where the user can specify multiple lines of input for his form. I want to iterate over all items in state.items[]
and build form input fields for them.
例如,表单以'field'和'autocomplete_from开头然后,用户可以点击添加新行以获取表单中的更多行。
E.g the form starts with 'field' and 'autocomplete_from. The user can then click add a new line to get more rows in his form.
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 );
推荐答案
在 .map
此不会引用您的组件。有多种方法可以解决此问题
In .map
this does not refer to your component., there are several ways how you can solve this issue
-
将
此
保存到变量
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>
);
}
设置此
for .map
callback(如果您不能使用 ES2015
功能,则此变体优先)
Set this
for .map
callback(if you can't use ES2015
features, this variant is prefered)
this.state.items.map(function (object, i) {
// ....
}, this);
使用箭头功能
this.state.items.map((object, i) => {
// ....
})
使用 .bind
this.state.items.map(function(object, i) {
// ....
}.bind(this))
这篇关于React:this.state在for循环中消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!