将event.target与React组件一起使用 [英] Using event.target with React components
问题描述
我的项目遇到了一些麻烦。任何人都可以向我解释为什么我不能使用 e.target
来访问 className
以外的任何内容?
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
?
以下是我入口点的代码:
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 Menu component, using the update
method. See Menu below:
module.exports = class Menu extends React.Component {
render (){
return (
<div>
<Button space="home" className="home" txt="Home" onClick={this.props.onClick}/>
</div>
)
}
}
我真的想知道为什么我可以访问 txt
和空格
使用 e.target
的值。我已阅读文档并寻找其他来源,但我还没有答案,但我希望有办法可以做到。
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.
推荐答案
update
方法中的第一个参数是 SyntheticEvent
对象包含任何 event
,它不是对React组件的引用,其中有属性道具
。
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
.
如果你需要传递参数来更新方法你就可以这样做
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
并获取这些参数在更新
方法
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
为您提供本机 DOMNode
,然后您需要使用常规DOM API来访问属性。例如 getAttribute
或数据集
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or 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);
}
这篇关于将event.target与React组件一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!