小编典典

将event.target与React组件一起使用

reactjs

我的项目遇到了麻烦。谁能向我解释为什么我不能使用e.target来访问className

下面是我的切入点的代码:

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>
    )

  }
}

我正在尝试使用该方法访问“ 菜单” 组件中的设置update。请参阅下面的 菜单

module.exports = class Menu extends React.Component {

    render (){
       return (
           <div>
               <Button space="home" className="home" txt="Home" onClick={this.props.onClick}/>

        </div>
       )

    }
}

我真的很想知道为什么我可以使用来访问txtspacee.target。我已经阅读了文档并寻找了其他资源,但是我还没有答案,但是我希望有办法可以做到。


阅读 346

收藏
2020-07-22

共1个答案

小编典典

updatemethod中的第一个参数是SyntheticEvent包含任何属性和方法的对象event,它不引用存在属性的React组件props

如果您需要传递参数来更新方法,可以这样做

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

并在update方法中获取这些参数

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target为您提供native DOMNode,那么您需要使用常规的DOM
API来访问属性。例如getAttributedataset

<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);
}

Example

2020-07-22