Javascript 获取被单击的元素
JSXJavascript 获取被单击的元素,javascript,jquery,reactjs,Javascript,Jquery,Reactjs,JSX let MY = React.createClass({ sendMsg : function(e){ alert($(e.target).attr('data-id')); //sendMsgButton = ?? }, render: function() { return ( <button is class = "send_msg" data-id = "10" onClick = {
let MY = React.createClass({
sendMsg : function(e){
alert($(e.target).attr('data-id'));
//sendMsgButton = ??
},
render: function() {
return (
<button is class = "send_msg"
data-id = "10"
onClick = {
this.sendMsg
} >
Send Message
<span> INSIDE SPAN </span> <span className = "sendMsgIcon" > ICON </span> </button>
);
}
});
ReactDOM.render(
<MY />,
document.getElementById("container")
);
如何获得确切的元素 您应该使用
e.currentTarget
而不是e.target
例如:
sendMsg : function(e){
alert($(e.currentTarget).attr('data-id'));
//sendMsgButton = ??
}
希望这有帮助 使用react可以避免使用Jquery和DOM选择器
let MY=React.createClass({
sendMsg:函数(e){
警报(this.button.getAttribute('data-id');
//sendMsgButton=??
},
render:function(){
返回(
{this.button=button;}}
onClick={
这是sendMsg
} >
发送消息
内跨距图标
);
}
});
与您的问题无关,但为了避免使用jQuery和读取数据表单DOM,我会这样做
let Button=React.createClass({
_onClick:函数(e){
e、 预防默认值();
this.props.onClick(e,this)
},
getSomeAttr:function(){
返回this.props.someAttr;
},
render:function(){
返回(
发送消息
内跨
偶像
);
}
});
让我的=React.createClass({
sendMsg:函数(e,btn){
警报(btn.getSomeAttr());
},
render:function(){
返回(
);
}
});
ReactDOM.render(
,
document.getElementById(“容器”)
);
仅使用一个类不能实现这一点吗?
sendMsg : function(e){
alert($(e.currentTarget).attr('data-id'));
//sendMsgButton = ??
}
let MY = React.createClass({
sendMsg : function(e){
alert(this.button.getAttribute('data-id'));
//sendMsgButton = ??
},
render: function() {
return (
<button is class = "send_msg"
data-id = "10"
ref={(button) => { this.button = button; }}
onClick = {
this.sendMsg
} >
Send Message
<span> INSIDE SPAN </span> <span className = "sendMsgIcon" > ICON </span> </button>
);
}
});
let Button = React.createClass({
_onClick: function(e){
e.preventDefault();
this.props.onClick(e, this)
},
getSomeAttr: function(){
return this.props.someAttr;
},
render : function() {
return (
<button onClick={this._onClick}>
Send Message
<span> INSIDE SPAN </span>
<span className = "sendMsgIcon"> ICON </span>
</button>
);
}
});
let MY = React.createClass({
sendMsg : function(e, btn){
alert(btn.getSomeAttr());
},
render: function() {
return (
<Button someAttr="10" onClick={this.sendMsg}/>
);
}
});
ReactDOM.render(
<MY />,
document.getElementById("container")
);