代码之家  ›  专栏  ›  技术社区  ›  Ashh

在reactjs中从父函数调用子函数

  •  0
  • Ashh  · 技术社区  · 6 年前

    我的父组件

    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 从父组件。我试过了 this 但不起作用。

    编辑

    升级后我得到这个

    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
    

    call child function from parent in react 16

    2 回复  |  直到 5 年前
        1
  •  1
  •   Shannon Johnstone    6 年前

    React文档有一个使用refs的例子

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

    我还想知道想要这样做的用例,也许一些上下文可以帮助你找到答案?

        2
  •  1
  •   aravind_reddy    6 年前

    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)