在reactJS类的render函数中,我有以下按钮,它触发confirmRemove
<a href='#'
className='content-icon'
title='Remove entry'
onClick={this.confirmRemove}>
<%= image_tag("form/remove.png") %>
</a>
在confirmRemove
(它的咖啡脚本)中,创建了一个magnificPop:
confirmRemove: (e) ->
e.preventDefault()
$.magnificPopup.open(
{
items: {
type: 'inline',
src: $(
'<div className="white-popup">
<h4>Do you really want to remove this entry from the playlist?</h4>
<button id="test-popup-no">No</button>
<button id="test-popup-yes">Yes</button>
</div>'
)
},
type: 'inline',
midClick: true
}
)
$('#test-popup-yes').click ->
$.magnificPopup.close()
$.ajax
type: 'PUT'
dataType: 'JSON'
url: "/xxx/#{@props.xxxId}/remove_entry"
data:
'_method': 'PUT'
'xxx_id': @props.id
beforeSend: =>
$.status_message 'Removing xxx', 0
@props.onDeleteStart()
success: (data) =>
$.success_message 'Successfully removed xxx'
@props.onDeleteCommit()
error: (data) =>
$.error_message 'Error removing xxx'
@props.onDeleteFailure()
但点击test-popup-yes
按钮后,我得到了detailed error: TypeError: this.props is undefined
我认为这是一个范围问题,任何关于在点击功能中访问@props的想法。
答案 0 :(得分:1)
你是对的,这是一个范围问题。由于this
在您通过调用新函数更改范围时经常更改,因此您无法使用它来访问原始值。
您可以通过两种方式解决此问题。
this
与点击处理程序中的外部作用域绑定。示例:
$('#test-popup-yes').click =>
this
,以便您仍然可以访问此原始值。示例:
confirmRemove: (e) ->
e.preventDefault()
that = this //aliasing this to that
...
$('#test-popup-yes').click ->
$.magnificPopup.close()
$.ajax
type: 'PUT'
dataType: 'JSON'
url: "/xxx/#{that.props.xxxId}/remove_entry"
data:
'_method': 'PUT'
'xxx_id': that.props.id
beforeSend: =>
$.status_message 'Removing xxx', 0
that.props.onDeleteStart()
success: (data) =>
$.success_message 'Successfully removed xxx'
that.props.onDeleteCommit()
error: (data) =>
$.error_message 'Error removing xxx'
that.props.onDeleteFailure()