簡體   English   中英

在reactjs中從父級調用子函數

[英]call child function from parent in reactjs

我的父組件

import EditReview from './partials/editReview'

class VenueDetails extends Component {
  constructor(props) {
    super(props)
    this.child = React.createRef();
  }
  render() {
    return (
      <div className="place-review-text">
        <EditReview {...this.props}/>
      </div>
    )
  }
}

我的子組件

class EditReview extends Component {
  onEditClick(review, editIndex) {
    console.log('ppp')
  }

  render() {
    const { handleSubmit, user, pristine, index, commentCrossClick } = this.props
    return (
      <div>
        <Field
          name="content"
          component={renderTextArea}
          className="form-control"
          label="Write your review..."
          rows={2}
        />
      </div>
    )
  }
}

export default EditReview

我需要從父組件調用onEditClick 我試過這個,但不起作用。

請幫助我

編輯

升級后我得到這個

Error in ./~/react-dom/lib/ReactServerRendering.js
Module not found: 'react/lib/React' in /home/user/ashish/LTC/lovethesecities-frontend/node_modules/react-dom/lib

解決所有錯誤后,在 react 16 中從父級調用子函數

React 文檔有一個使用 refs 的例子

https://reactjs.org/docs/refs-and-the-dom.html

我也想知道想要這樣做的用例,也許某些上下文可以幫助回答?

嘗試這樣做:

import EditReview from './partials/editReview'

class VenueDetails extends Component {
  render() {
    return (
      <div className="place-review-text">
        <EditReview ref={Ref => this.child=Ref } {...this.props} />
      </div>
    )
  }
}

並將父組件中的函數調用為this.child.onEditClick(param1,param2)

編輯1

如果您必須使用 react 15.x 本身來做,您可以做的是在父級中創建函數並將其作為道具傳遞給子級

暫無
暫無

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

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