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 函数
基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
