Javascript 将 event.target 与 React 组件一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37639122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using event.target with React components
提问by LucyViolet
I am having some trouble with my project. Can anyone explain to me why I can't use the e.target
to access anything other than className
?
我的项目遇到了一些问题。任何人都可以向我解释为什么我不能使用e.target
访问除 之外的任何内容className
?
Below is the code from my entry point:
以下是我的入口点的代码:
import React from 'react'
import ReactDOM from 'react-dom'
import Button from './Button'
import Menu from './Menu'
function test(e){
console.log(e.target.ref)
}
module.exports = class Content extends React.Component {
constructor(props){
super(props)
this.state={content: ''}
}
update(e){
console.log(e.target.txt)
}
render (){
return (
<div id="lower">
<div id="menu">
<Menu onClick={this.update.bind(this)}/>
</div>
<div id="content">
{this.state.content}
</div>
</div>
)
}
}
I am trying to access the setting in the Menucomponent, using the update
method. See Menubelow:
我正在尝试使用该方法访问Menu组件中的设置update
。请参阅以下菜单:
module.exports = class Menu extends React.Component {
render (){
return (
<div>
<Button space="home" className="home" txt="Home" onClick={this.props.onClick}/>
</div>
)
}
}
I really want to know why I can access the txt
and space
value using e.target
. I have read the documentation and looked for other sources but I have no answer yet, but I am hoping there is a way it can be done.
我真的想知道为什么我可以访问txt
和space
使用值e.target
。我已经阅读了文档并寻找了其他来源,但我还没有答案,但我希望有一种方法可以做到。
回答by Alexander T.
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
update
方法中的第一个参数是SyntheticEvent
包含任何通用属性和方法的对象event
,它不是对有属性的 React 组件的引用props
。
if you need pass argument to update method you can do it like this
如果您需要将参数传递给更新方法,您可以这样做
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
并在update
方法中获取这些参数
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
event.target
为您提供 native DOMNode
,那么您需要使用常规 DOM API 来访问属性。例如getAttribute
或dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}