如果我点击红色方块,有人可以告诉我如何检索data-custom
属性值吗?我不想在子项中放置相同的属性,因为如果我有更多和更深层次的嵌套元素,它会变得冗长。
class Example extends React.Component {
constructor(props){
super(props)
this.onClick = this.onClick.bind(this)
}
render(){
return (
<div className="large-box" data-custom="iExist" onClick={this.onClick}>
<div className="box red"></div>
</div>
)
}
onClick(e){
console.log(e.target.getAttribute('data-custom'))
}
}
ReactDOM.render(<Example />,document.getElementById('app'))
&#13;
.large-box {
display:flex;
width:200px;
height:100px;
border:1px solid black;
}
.box {
margin:auto auto;
width:40px;
height:40px;
}
.red{background-color:red;}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;
答案 0 :(得分:3)
简单 - 使用event.currentTarget
来自:https://developer.mozilla.org/en-US/docs/Web/API/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 Example extends React.Component {
constructor(props){
super(props)
this.onClick = this.onClick.bind(this)
}
render(){
return (
<div className="large-box" data-custom="iExist" onClick={this.onClick}>
<div className="box red"></div>
</div>
)
}
onClick(e){
console.log(e.currentTarget.getAttribute('data-custom'))
}
}
ReactDOM.render(<Example />,document.getElementById('app'))
&#13;
.large-box {
display:flex;
width:200px;
height:100px;
border:1px solid black;
}
.box {
margin:auto auto;
width:40px;
height:40px;
}
.red{background-color:red;}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;
答案 1 :(得分:1)
只需使用data-custom
方法检查属性hasAttibute
即可。如果属性不存在,则从parentNode
获取。
class Example extends React.Component {
constructor(props){
super(props)
this.onClick = this.onClick.bind(this)
}
render(){
return (
<div className="large-box" data-custom="iExist" onClick={this.onClick}>
<div className="box red"></div>
</div>
)
}
onClick(e){
console.log(e.target.hasAttribute('data-custom')?e.target.getAttribute('data-custom'):e.target.parentNode.getAttribute('data-custom'))
}
}
ReactDOM.render(<Example />,document.getElementById('app'))
&#13;
.large-box {
display:flex;
width:200px;
height:100px;
border:1px solid black;
}
.box {
margin:auto auto;
width:40px;
height:40px;
}
.red{background-color:red;}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;