React event.stopPropagation()没有停止导航

时间:2018-03-27 18:12:41

标签: reactjs

我是React的新手,并坚持以下方案。我想在点击此链接后停止导航。我做错了吗?

class Todo extends React.Component {
    handleRemoveClick(event, id) {
        console.log(id);
        console.log(event);
        event.stopPropagation();
        this.props.onRemoveClick(event,id);
    }
    render() {
        return (
        <li>{this.props.item.text}
            <a href="#">
              <span className="glyphicon glyphicon-remove" 
              onClick={()=>this.handleRemoveClick(event,this.props.item.id)}></span>
            </a>
        </li>
        );

    }
}

2 个答案:

答案 0 :(得分:2)

你没有这样的事件。

<li>{this.props.item.text}
        <a href="#">
          <span className="glyphicon glyphicon-remove" 
          onClick={(event)=>this.handleRemoveClick(event,this.props.item.id)}></span>
        </a>
</li>

答案 1 :(得分:1)

我不建议在React中使用render内的箭头函数。这里解释了原因:Why arrow functions and bind in React's render are problematic

如上所述,您的解决方案应该符合以下方面:

class Todo extends React.Component {
    handleRemoveClick = id => event => {
        console.log(id);
        console.log(event);
        event.preventDefault();
        this.props.onRemoveClick(event,id);
    }
    render() {
        return (
        <li>{this.props.item.text}
            <a href="#">
              <span 
                className="glyphicon glyphicon-remove" 
                onClick={this.handleRemoveClick(this.props.item.id)} 
              />
            </a>
        </li>
        );

    }
}