簡體   English   中英

如何在ReactJS的父組件內部獲取事件目標

[英]How to get the event target inside the parent component in ReactJS

我有一個帶有代碼的主要組件

changeColor = (color) => {

}

toggle = (e) => {
  console.log(e.target)
}

<div>
  <EditComponent changeColor={this.changeColor.bind(this)}>
  <TextComonent toggle={this.toggle.bind(this)}>
</div>

編輯組件

color = (value) => {
  this.props.changeColor(value)
}
<div>
  <button value='red' onClick={this.color.bind(this,"red")}>Red</button>
  <button value='blue' onClick={this.color.bind(this,"blue")}>Blue</button>
</div>

文字部分

toggle = (e) => {
  this.props.toggle(e)
}
<div>
  <p class="black-color" onClick={this.toggle.bind(this)}>Text 1</p>
  <p class="black-color" onClick={this.toggle.bind(this)}>Text 2</p>
</div>

我將首先單擊Text 1Text 2然后在toggle功能中獲取event 接下來,我將單擊RedBlue按鈕。 然后,我想將類更改為我之前單擊過的特定Text red-colorblue-color 如何在父組件中獲取事件以查找特定text或者有其他方法可以做到這一點?

我想在Parent組件中獲取event.target 我在父對象中獲得了event對象,但event.targetnull

<div>
 <EditComponent changeColor={this.changeColor.bind(this)}>
 <TextComonent toggle={this.toggle}>
 </div>

嘗試這種方式不要在父組件中綁定功能,然后嘗試,您將獲得目標

您沒有正確使用“綁定”。 您不需要與匿名函數綁定。

class Hello extends React.Component {
  render() {
    return (
    <div>
      <p onClick={(e) => this.toggle(e)}>
        Test
      </p>
    </div>);
  }

  toggle = (e) => {
    console.log(e.target.innerText);
    }
}

通過切換事件變量,可以根據需要執行更改。

我找到了添加event.persist();的確切解決方案event.persist(); 在父組件中獲取event.target

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM