2016-04-28 167 views
1

我碰到過這樣的問題: 有mousedown處理程序和子元素的父元素。React模板鼠標事件在容器的鼠標事件後觸發

如果我需要通過創建子事件之前,鼠標按下處理器陣營裏

var mousedown = function(e) { console.log('child-2: mousedown') }; 
    var childTemplate = React.createClass({ 
    render: function() { 
     return React.createElement("rect", {id: "child-2", x: "220", y: "220", width: "30", height: "30", onMouseDown: mousedown, fill: "blue"}); 
    } 
    }); 

    var template = React.createElement(childTemplate, {}); 
    ReactDOM.render(template, document.getElementById('area')); 

然後父鼠標按下火災模板添加子元素(jsfiddle example)

有沒有辦法先強迫孩子鼠標按下(並阻止父母的鼠標按下與例如e.stopPropagation)而不重寫反應模板中的所有內容?

回答

1

因爲您正在使用jQuery處理某些事件處理程序,而針對其他事件處理程序使用jQuery,因此事件順序不能僅通過e.stopPropagation進行管理。根據我所做的一些測試,甚至沒有發生事件冒泡。

解決方法是使用React來管理所有內容,但如果這不是一個選項,您可以明確地檢查您點擊哪個組件,並在需要時停止運行parent

例如:

$('#parent').unbind('mousedown').bind('mousedown', function(e) { 
    if(e.target.id != "parent") return; //if not "#parent" don't proceed. 
    console.log('parent: mousedown'); 
}); 

通過傳遞事件對象到事件處理程序,您可以檢查被點擊哪個元素。如果我們點擊任何元素不是parent,然後返回。如果元素點擊確實parent ID,那麼它將執行控制檯日誌。

這裏是一個完整的演示:Fiddle

$(document).ready(function() { 
    $('#parent').unbind('mousedown').bind('mousedown', function(e) { 
    if(e.target.id != "parent") return; 
    console.log('parent: mousedown'); 
    }); 

    $('#child-1').on('mousedown', function() { 
    console.log('child-1: mousedown'); 
    }); 

    var mousedown = function(e) { 
    console.log('child-2: mousedown') 
    }; 

    var childTemplate = React.createClass({ 
    render: function() { 
     return React.createElement("rect", {id: "child-2", x: "220", y: "220", width: "30", height: "30", onMouseDown: mousedown, fill: "blue"}); 
    } 
    }); 

    var template = React.createElement(childTemplate, {}); 
    ReactDOM.render(template, document.getElementById('area')); 
}); 
+0

我害怕它。你能否說這是否真的是一個反應的缺陷(特徵),還是這是一種常見的預期行爲? 無論如何謝謝您的詳細解答 – user1820686

+0

我無法肯定地說,但jQuery並非真正意義上與Reactjs合作,反之亦然。所以這不是一個錯誤(因爲它們不是爲了一起工作),但它也不是故意的效果。 – Chris