我正在使用 react 。我不太清楚我应该如何编写事件处理程序,以便当我单击 a
时,我可以提醒 data-href。现在如果我点击 div 或 img,它会触发一个事件,但由于目标实际上不是 a
,它会提示 null,这不是我想要的。
test(e){alert(e.target.getAttribute('data-href'))}
<div>
<ui>
<li >
<a data-href = 'http://cnn.com' onClick = {e = > this.test(e)>
<div>
<img src = 'someimage.jpg'}>
hi there
</div>
</a>
<li>
</ui>
</div>
编辑:
像这样的 conversationList() & selectConversation() 就是我这里说的~
import React from 'react';
import { connect, Provider } from 'react-redux';
import fetch from 'isomorphic-fetch';
import * as actions from './actions/index';
import io from 'socket.io-client';
class Chat extends React.Component{
constructor(props){
super(props);
this.state = {recipientId: '', messageBuffer:'asdfadsfasdf'};
this.userList = this.userList.bind(this);
this.changeRecipient = this.changeRecipient.bind(this);
this.insertText = this.insertText.bind(this);
}
componentWillMount(){
this.props.loadConversationsSocket();
this.props.loadConversations();
this.props.loadRecipients();
}
participantsNames(participants){
console.log('in par ');
console.log(participants);
return participants.map(participant => (<div key= {participant._id}>{participant.name}</div>));
}
selectConversation(e){
e.preventDefault();
console.log(this.tagName);
let data = this.getAttribute('data-href');
alert(data);
}
conversationList(){
if(!(this.props.conversations.length === 0)){
console.log('in conversation if');
return this.props.conversations.map(conversation =>(<li key = {conversation.conversation._id} >
<a data-href = {'http://localhost:8000/messaages/'+conversation.conversation._id} onClick = {(e)=>this.selectConversation(e)}>
<div>
participants: {this.participantsNames(conversation.conversation.participants)}
</div>
<div>
{conversation.message[0].auther}
{conversation.message[0].body}
</div>
</a>
</li>))
}
}
render(){
return (
<div>
<ul>
{this.conversationList()}
</ul>
</div>)
}
}
function mapStateToProps(state) {
return { recipients: state.recipients, conversations: state.conversations};
}
export default connect(mapStateToProps, actions)(Chat);
最佳答案
您的 onClick
处理程序附加到 img
,而不是 a
。这是第一个问题。
然后你应该更新你的代码来查询event.currentTarget
。
event.currentTarget
- identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.
你应该这样写你的事件处理程序:
class Hello extends React.Component {
test(e){
alert(e.currentTarget.getAttribute('data-href'))
}
render() {
return (
<div>
<a onClick={this.test} data-href="foo">
<img src="https://vignette.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437" />
<div>clickMe</div>
</a>
</div>
);
}
}
我还建议阅读 this article关于处理事件。
关于javascript - React - 事件冒泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47710816/