如何将 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 );
最佳答案
在 .map
this 中没有引用你的组件,有几种方法可以解决这个问题
保存
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> ); }
为
.map
回调设置this
(如果你不能使用ES2015
特性,这个变体是首选)this.state.items.map(function (object, i) { // .... }, this);
使用
箭头函数
this.state.items.map((object, i) => { // .... })
使用
.bind
this.state.items.map(function(object, i) { // .... }.bind(this))
关于javascript - React : this.状态在for循环中消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29517715/