问题描述
我使用文章作为例子(React)方式),但它不适合我。请指出我的错误,因为我无法理解什么是错的。
I used this article as an example (React way), but it is not working for me. Please point me to my mistake, as I can't understand what's wrong.
这是我看到的错误:
这是我的代码:
// PARENT
var SendDocModal = React.createClass({
getInitialState: function() {
return {tagList: []};
},
render: function() {
return (
<div>
{
this.state.tagList.map(function(item) {
return (
<TagItem nameProp={item.Name} idProp={item.Id} onClick={this.HandleRemove}/>
)
})
}
</div>
)
},
HandleRemove: function(c) {
console.log('On REMOVE = ', c);
}
});
// CHILD
var TagItem = React.createClass({
render: function() {
return (
<span className="react-tagsinput-tag">
<span>{this.props.nameProp}</span>
<a className='react-tagsinput-remove' onClick={this.HandleRemove}></a>
</span>
)
},
HandleRemove: function() {
this.props.onClick(this);
}
});
提前致谢!
推荐答案
问题是地图
回调中的此
未引用React组件,因此 this.HandleRemove
是 undefined
。
The issue is that this
inside the map
callback does not refer to the React component, hence this.HandleRemove
is undefined
.
你可以通过将第二个参数传递给 map
来显式设置此
值:
You can set the this
value explicitly by passing a second argument to map
:
this.state.tagList.map(function() {...}, this);
现在此
里面回调引用与相同的值
外部回调,即 SendDocModal
实例。
Now this
inside the callback refers to the same value as this
outside the callback, namely the SendDocModal
instance.
这与React无关,它只是JavaScript的工作方式。请参阅了解更多信息和其他解决方案。
This has nothing to do with React, it's just how JavaScript works. See How to access the correct `this` context inside a callback? for more info and other solutions.
这篇关于React.js:从子到父的onClick函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!