如何从父组件调用子组件方法

在我的 Reactjs 应用程序中,我需要有一个名为Wizard.js的父组件(一个向导)和一些名为PrimaryForm.js、 SecondaryForm.js 等的子组件(向导的步骤)。它们都是基于类的组件,有一些本地验证功能。


用于推进步骤的“上一步”和“下一步”按钮位于 Wizard.js 中。


为了推进向导的下一步,我试图从 PrimaryForm 调用一个方法。我在 Stackoverflow 中检查了类似的问题;尝试使用 ref 或 forwardRef,但我无法使其工作。我目前收到“类型错误:无法读取 null 的属性‘handleCheckServer’ ”错误。


下面是我的父子类。任何有关我将做错的事情的帮助表示赞赏。


向导.js:


import React, { Component } from 'react';

...


const getSteps = () => {

  return [

    'Info',

    'Source Details',

    'Target Details',

    'Configuration'

  ];

}


class Wizard extends Component {

  constructor(props) {

    super(props);

    this.firstRef = React.createRef();

    this.handleNext = this.handleNext.bind(this);


    this.state = {

      activeStep: 1,

    }

}


  componentDidMount() {}


  handleNext = () =>  {

    if (this.state.activeStep === 1) {

      this.firstRef.current.handleCheckServer(); <<<<<<<<<<<<<<<<< This is where I try to call child method

    }

    this.setState(state => ({

      activeStep: state.activeStep + 1,

    }));

  };


  handleBack = () => {

    this.setState(state => ({

      activeStep: state.activeStep - 1,

    }));

  };


  handleReset = () => {

    this.setState({

      activeStep: 0,

    });

  };


  render() {

    const steps = getSteps();

    const currentPath = this.props.location.pathname;

    const { classes } = this.props;


    return (

      <React.Fragment>

        <CssBaseline />

        <Topbar currentPath={currentPath} />

        <div className={classes.root}>

          <Grid container spacing={2} justify="center" direction="row">

            <Grid container spacing={2} className={classes.grid} justify="center" direction="row">

              <Grid item xs={12}>

                <div className={classes.topBar}>

                  <div className={classes.block}>

                    <Typography variant="h6" gutterBottom>Wizard</Typography>

                    <Typography variant="body1">Follow the wizard steps to create a configuration.</Typography>

                  </div>

                </div>

              </Grid>



慕的地10843
浏览 171回答 1
1回答

皈依舞

打字稿中的示例。这个想法是父级将其回调传递给子级。孩子调用父母的回调,提供自己的例如子回调作为参数。父级将它得到的(子回调)存储在一个类成员变量中并稍后调用它。import * as React from 'react'interface ICallback {&nbsp; (num: number): string}type ChildProps = {&nbsp; parent_callback: (f: ICallback) => void;}class Child extends React.Component {&nbsp; constructor(props: ChildProps) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; props.parent_callback(this.childCallback);&nbsp; }&nbsp; childCallback: ICallback = (num: number) => {&nbsp; &nbsp; if (num == 5) return "hello";&nbsp; &nbsp; return "bye";&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; <div>Child</div>&nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp; )&nbsp; }}class Parent extends React.Component {&nbsp; readonly state = { msg: "<not yet set>" };&nbsp; letChildRegisterItsCallback = (fun: ICallback) => {&nbsp; &nbsp; this.m_ChildCallback = fun;&nbsp; }&nbsp; callChildCallback() {&nbsp; &nbsp; const str = this.m_ChildCallback? this.m_ChildCallback(5) : "<callback not set>";&nbsp; &nbsp; console.log("Child callback returned string: " + str);&nbsp; &nbsp; return str;&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; this.setState((prevState) => { return {...prevState, msg: this.callChildCallback()} });&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; <Child {...{ parent_callback: this.letChildRegisterItsCallback }} />&nbsp; &nbsp; &nbsp; &nbsp; <div>{this.state.msg}</div>&nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp; )&nbsp; }&nbsp; m_ChildCallback: ICallback | undefined = undefined;}PSJavascript 中的相同代码。唯一的区别是interface, type, readonly去掉了和类型注解。粘贴到此处确认它是有效的 ES2015 stage-2 代码。class Child extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; props.parent_callback(this.childCallback);&nbsp; }&nbsp; childCallback = (num) => {&nbsp; &nbsp; if (num == 5) return "hello";&nbsp; &nbsp; return "bye";&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; <div>Child</div>&nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp; )&nbsp; }}class Parent extends React.Component {&nbsp; state = { msg: "<not yet set>" };&nbsp; letChildRegisterItsCallback = (fun) => {&nbsp; &nbsp; this.m_ChildCallback = fun;&nbsp; }&nbsp; callChildCallback() {&nbsp; &nbsp; const str = this.m_ChildCallback? this.m_ChildCallback(5) : "<callback not set>";&nbsp; &nbsp; console.log("Child callback returned string: " + str);&nbsp; &nbsp; return str;&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; this.setState((prevState) => { return {...prevState, msg: this.callChildCallback()} });&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; <Child {...{ parent_callback: this.letChildRegisterItsCallback }} />&nbsp; &nbsp; &nbsp; &nbsp; <div>{this.state.msg}</div>&nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp; )&nbsp; }&nbsp; m_ChildCallback = undefined;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript