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 函数


基础教程推荐
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01