javascript - React - 事件冒泡

标签 javascript reactjs

我正在使用 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/

相关文章:

android - React Native 中 View 的网格布局

javascript - 使用 Angular 平移进行本地化

javascript - 单击时无法更改图像。图像只改变一次,但不会变回来

javascript - 反跳 react 选择 graphql 查询

javascript - React - 每个样式元素的组件?

node.js - SSE - 服务器发送的事件 - 如何重用相同的 EventSource

javascript - 是否可以在 Javascript 的 Split Regexp 中连接变量?例如 : var. split(/[A-Z]/+ 变量 +/\d/);

javascript - 如何计算javascript中的日出和日落?

javascript - 如何使用 URLDecode 之类的东西取回 html 格式的文本

javascript - d3 v5 轴比例更改平移方式太多