如何知道发生事件的父组件

时间:2018-04-12 03:09:01

标签: reactjs

在"书"组件我有这个:

<select value={this.props.value} onChange={this.onShelfChange}>
                <option>Currently Reading</option>
                <option>Want to Read</option>
                <option>Read</option>
                <option>None</option>
</select>

onChange触发此功能(在同一组件中)

onShelfChange(e){
    //get the newShelf from the 'select'
    let newShelf = e.target.value


    if(newShelf==="Want to Read"){
      newShelf = "wantToRead"
       }
    else if(newShelf==="Read"){
      newShelf = "read"
            }
    else if(newShelf==="Currently Reading"){
      newShelf = "currentlyReading"
            }

    //get the bookID passed from parent component
    const bookID = this.props.bookID

    console.log(bookID)
    console.log(newShelf)

    //call the function that was passed as prop
    this.props.onShelfUpdate(bookID, newShelf)
  }: 

prop.onShelfUpdate由父母1给出。我希望能够调用父母2中的另一个onShelfUptade。为此,我需要从WHICH中的一个父母知道架子上的变化,所以做类似的事情:

    if (it comes from parent 1){
this.props.onShelfUpdateParent1
    }
else if (it comes from parent 2){
this.props.onShelfUpdateParent2
}

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以通过回调使用,例如:

你的渲染

<select value={this.props.value} onChange={(e) => this.onShelfChange(e, this.props.callback)}>
  <option>Currently Reading</option>
  <option>Want to Read</option>
  <option>Read</option>
  <option>None</option>
</select>

您的处理

onShelfChange(e, callback) {
  //get the newShelf from the 'select'
  let newShelf = e.target.value

  if(newShelf==="Want to Read"){
    newShelf = "wantToRead"
  }
  else if(newShelf==="Read"){
    newShelf = "read"
  }
  else if(newShelf==="Currently Reading"){
    newShelf = "currentlyReading"
  }

  //get the bookID passed from parent component
  const bookID = this.props.bookID

  console.log(bookID)
  console.log(newShelf)

  //call the function that was passed as prop
  // this.props.onShelfUpdate(bookID, newShelf)
  // callback for dynamic function
  callback(bookID, newShelf)
}

假设Dropdown的渲染选择调用。所以你可以像这样通过父母:

<Dropdownn callback={this.handleUpdateByParentApp} />

或来自父母2

<Dropdownn callback={this.handleUpdateByParent2App} />
记得,你必须设置2个参数,因为你打电话给2个参数。