React.js: onClick function from child to parent(React.js:从子到父的 onClick 函数)
问题描述
我以这篇文章为例(React方式),但它对我不起作用.请指出我的错误,因为我不明白出了什么问题.
这是我看到的错误:
<块引用>未捕获的类型错误:this.props.onClick 不是函数
这是我的代码:
//父级var SendDocModal = React.createClass({获取初始状态:函数(){返回{标签列表:[]};},渲染:函数(){返回 (
{this.state.tagList.map(function(item) {返回 (<TagItem nameProp={item.Name} idProp={item.Id} onClick={this.HandleRemove}/>)})}</div>)},处理删除:函数(c){console.log('On REMOVE = ', c);}});//孩子var TagItem = React.createClass({渲染:函数(){返回 (<span className="react-tagsinput-tag"><span>{this.props.nameProp}</span><a className='react-tagsinput-remove' onClick={this.HandleRemove}></a></span>)},处理删除:函数(){this.props.onClick(this);}});
提前致谢!
问题是 map
回调中的 this
没有引用 React 组件,因此 this.HandleRemove
是 undefined
.
您可以通过将第二个参数传递给 map
来显式设置 this
值:
this.state.tagList.map(function() {...}, this);
现在this
inside回调指的是与this
相同的值outside回调,即SendDocModal
实例.
这与 React 无关,它只是 JavaScript 的工作方式.请参阅 如何访问正确的 `this` 上下文回调?了解更多信息和其他解决方案.
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.
This is the error I see:
Uncaught TypeError: this.props.onClick is not a function
Here is my code:
// 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);
}
});
Thanks in advance!
The issue is that this
inside the map
callback does not refer to the React component, hence this.HandleRemove
is undefined
.
You can set the this
value explicitly by passing a second argument to map
:
this.state.tagList.map(function() {...}, this);
Now this
inside the callback refers to the same value as this
outside the callback, namely the SendDocModal
instance.
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 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:React.js:从子到父的 onClick 函数


- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01