You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React低于16版本如何通过函数式父组件调用另一类子组件方法

方案实现

因为使用的React版本低于16,无法使用Hooks,我们采用父组件作为中介+ref获取C1实例的方案实现需求,全程不引入任何第三方工具,兼容低版本React:

1. 父组件修改

低于16.8版本的函数组件无法存储实例引用,我们先把父组件改为类组件,通过回调ref获取C1的实例,再把触发C1提交的方法传递给C2:

import React from 'react';
import C1 from './C1';
import C2 from './C2';

export default class Parent extends React.Component {
  constructor(props) {
    super(props);
    // 存储C1组件的实例引用
    this.c1Ref = null;
  }

  // 触发C1的提交方法
  triggerC1Submit = () => {
    if (this.c1Ref) {
      this.c1Ref.submitC1();
    }
  }

  render() {
    return (
      <div>
        <C1 ref={(instance) => { this.c1Ref = instance; }} />
        <C2 onCheck={this.triggerC1Submit} />
      </div>
    );
  }
}

2. C1组件修改

将输入框改为受控组件,把输入值存在state里,同时调整submitC1逻辑兼容无event调用的场景:

class C1 extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '' // 存储输入框最新值
    };
    // 提前绑定this,避免重复bind
    this.submitC1 = this.submitC1.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(e) {
    this.setState({
      inputValue: e.target.value
    });
  }
  
  submitC1(event) {
    // 只有原生表单提交时存在event,阻止默认跳转行为
    if (event) {
      event.preventDefault();
    }
    // 直接取state里的最新输入值发起请求,不用依赖event.target
    const currentInput = this.state.inputValue;
    // 这里写你的API请求逻辑,请求成功后把返回结果存在父组件state,再传给C2展示即可
    console.log('发起请求,参数为:', currentInput);
  }
  
  render() {
    return (
      <div>
        <form onSubmit={this.submitC1}>
          <input 
            type="text" 
            value={this.state.inputValue}
            onChange={this.handleInputChange}
          />
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}

export default C1;

3. C2组件修改

直接绑定父组件传递的onCheck方法到Check按钮的点击事件即可:

class C2 extends React.Component{
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div>
        {/* 点击直接触发父组件传来的方法,即可调用C1的提交逻辑 */}
        <button onClick={this.props.onCheck}>Check</button>
        {/* 这里写你的返回数据展示逻辑 */}
      </div>
    );
  }
}

export default C2;

内容的提问来源于stack exchange,提问作者JS_lover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 20:57:03