搜索
首页web前端前端问答React父组件怎么调用子组件的方法

React父组件怎么调用子组件的方法

Dec 27, 2022 pm 07:01 PM
前端react.js

调用方法:1、类组件中的调用可以利用React.createRef()、ref的函数式声明或props自定义onRef属性来实现;2、函数组件、Hook组件中的调用可以利用useImperativeHandle或forwardRef抛出子组件ref来实现。

React父组件怎么调用子组件的方法

本教程操作环境:Windows7系统、react18版、Dell G3电脑。

在React中,我们经常在子组件中调用父组件的方法,一般用props回调即可。但是有时候也需要在父组件中调用子组件的方法,通过这种方法实现高内聚。有多种方法,请按需服用。

类组件中


1、React.createRef()

  • 优点:通俗易懂,用ref指向。

  • 缺点:使用了HOC的子组件不可用,无法指向真是子组件

    比如一些常用的写法,mobx的@observer包裹的子组件就不适用此方法。

import React, { Component } from 'react';

class Sub extends Component {
  callback() {
    console.log('执行回调');
  }
  render() {
    return <div>子组件</div>;
  }
}

class Super extends Component {
  constructor(props) {
    super(props);
    this.sub = React.createRef();
  }
  handleOnClick() {
    this.sub.callback();
  }
  render() {
    return (
      <div>
        <Sub ref={this.sub}></Sub>
      </div>
    );
  }
}

2、ref的函数式声明

  • 优点:ref写法简洁
  • 缺点:使用了HOC的子组件不可用,无法指向真是子组件(同上)

使用方法和上述的一样,就是定义ref的方式不同。

...

<Sub ref={ref => this.sub = ref}></Sub>

...

3、使用props自定义onRef属性

  • 优点:假如子组件是嵌套了HOC,也可以指向真实子组件。
  • 缺点:需要自定义props属性
import React, { Component } from &#39;react&#39;;
import { observer } from &#39;mobx-react&#39;

@observer
class Sub extends Component {
	componentDidMount(){
    // 将子组件指向父组件的变量
		this.props.onRef && this.props.onRef(this);
	}
	callback(){
		console.log("执行我")
	}
	render(){
		return (<div>子组件</div>);
	}
}

class Super extends Component {
	handleOnClick(){
       // 可以调用子组件方法
		this.Sub.callback();
	}
	render(){
		return (
          <div>
			<div onClick={this.handleOnClick}>click</div>
			<Sub onRef={ node => this.Sub = node }></Sub>	
	   	  </div>)
	}
}

函数组件、Hook组件


1、useImperativeHandle

  • 优点: 1、写法简单易懂 2、假如子组件嵌套了HOC,也可以指向真实子组件
  • 缺点: 1、需要自定义props属性 2、需要自定义暴露的方法
import React, { useImperativeHandle } from &#39;react&#39;;
import { observer } from &#39;mobx-react&#39;


const Parent = () => {
  let ChildRef = React.createRef();

  function handleOnClick() {
    ChildRef.current.func();
  }

  return (
    <div>
      <button onClick={handleOnClick}>click</button>
      <Child onRef={ChildRef} />
    </div>
  );
};

const Child = observer(props => {
  //用useImperativeHandle暴露一些外部ref能访问的属性
  useImperativeHandle(props.onRef, () => {
    // 需要将暴露的接口返回出去
    return {
      func: func,
    };
  });
  function func() {
    console.log(&#39;执行我&#39;);
  }
  return <div>子组件</div>;
});

export default Parent;

2、forwardRef

使用forwardRef抛出子组件的ref

这个方法其实更适合自定义HOC。但问题是,withRouter、connect、Form.create等方法并不能抛出ref,假如Child本身就需要嵌套这些方法,那基本就不能混着用了。forwardRef本身也是用来抛出子元素,如input等原生元素的ref的,并不适合做组件ref抛出,因为组件的使用场景太复杂了。

import React, { useRef, useImperativeHandle } from &#39;react&#39;;
import ReactDOM from &#39;react-dom&#39;;
import { observer } from &#39;mobx-react&#39;

const FancyInput = React.forwardRef((props, ref) => {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));

  return <input ref={inputRef} type="text" />
});

const Sub = observer(FancyInput)

const App = props => {
  const fancyInputRef = useRef();

  return (
    <div>
      <FancyInput ref={fancyInputRef} />
      <button
        onClick={() => fancyInputRef.current.focus()}
      >父组件调用子组件的 focus</button>
    </div>
  )
}

export default App;

总结

父组件调子组件函数有两种情况

  • 子组件无HOC嵌套:推荐使用ref直接调用
  • 有HOC嵌套:推荐使用自定义props的方式

【相关推荐:Redis视频教程编程教学

以上是React父组件怎么调用子组件的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
CSS:我可以在同一DOM中使用多个ID吗?CSS:我可以在同一DOM中使用多个ID吗?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

HTML5的目的:创建一个更强大,更容易访问的网络HTML5的目的:创建一个更强大,更容易访问的网络May 14, 2025 am 12:18 AM

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互动,可及可访问。1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

HTML5的重要目标:增强网络开发和用户体验HTML5的重要目标:增强网络开发和用户体验May 14, 2025 am 12:18 AM

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒体综合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityAncccossibility.2)和TagsallowsemplowsemplowseamemelesseamlessallowsemlessemlessemelessmultimedimeDiaiiaemediaiaembedwitWithItWitTplulurugIns.3)

HTML5:安全吗?HTML5:安全吗?May 14, 2025 am 12:15 AM

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrevulnerabilityLikeClickLickLickLickLickLickjAckJackJacking.2)

与较旧的HTML版本相比,HTML5目标与较旧的HTML版本相比,HTML5目标May 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS:使用ID选择器不好吗?CSS:使用ID选择器不好吗?May 13, 2025 am 12:14 AM

使用ID选择器在CSS中并非固有地不好,但应谨慎使用。1)ID选择器适用于唯一元素或JavaScript钩子。2)对于一般样式,应使用类选择器,因为它们更灵活和可维护。通过平衡ID和类的使用,可以实现更robust和efficient的CSS架构。

HTML5:2024年的目标HTML5:2024年的目标May 13, 2025 am 12:13 AM

html5'sgoalsin2024focusonrefinement和optimization,notnewfeatures.1)增强performandemandeffifice throughOptimizedRendering.2)risteccessibilitywithrefinedibilitywithRefineDatientAttributesAndEllements.3)expliencernsandelements.3)explastsecurityConcerns,尤其是withercervion.4)

HTML5试图改进的主要领域是什么?HTML5试图改进的主要领域是什么?May 13, 2025 am 12:12 AM

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供应,2)语义结构,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,简化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中