html子级怎样引用父级文件,从父级调用子方法

首先,让我表示一下,这通常是不在陆地上做出反应的方法。通常,您想要做的是将功能传递给道具中的子程序,并在事件中传递来自子级的通知(或者更好的是:dispatch).

但如果你必在子组件上公开一个命令式方法,您可以使用参考文献..记住,这是一个逃生舱口,通常表明一个更好的设计是可用的。以前,只支持基于类的组件。随着…的到来反应钩,现在不是这样了

使用钩子和函数组件(>= react@16.8)import React, { forwardRef, useRef, useImperativeHandle } from 'react';

// We need to wrap component in `forwardRef` in order to gain

// access to the ref object that is assigned using the `ref` prop.

// This ref is passed as the second parameter to the function component.const Child = forwardRef((props, ref) => {

// The component instance will be extended

// with whatever you return from the callback passed

// as the second argument

useImperativeHandle(ref, () => ({

getAlert() {

alert("getAlert from Child");

}

}));

return 

Hi

;});const Parent = () => {

// In order to gain access to the child component instance,

// you need to assign it to a `ref`, so we call `useRef()` to get one

const childRef = useRef();

return (

 childRef.current.getAlert()}>Click

);};

文件useImperativeHandle()是这里:useImperativeHandle时,自定义公开给父组件的实例值。ref.

使用类组件(>= react@16.4)class Parent extends Component {

constructor(props) {

super(props);

this.child = React.createRef();

}

onClick = () => {

this.child.current.getAlert();

};

render() {

return (

Click

);

}}class Child extends Component {

getAlert() {

alert('getAlert from Child');

}

render() {

return 

Hello

;

}}ReactDOM.render(, document.getElementById('root'));

遗留API(<= react@16.3)

出于历史目的,下面是在16.3之前的Reaction版本中使用的基于回调的样式:

const { Component } = React;

const { render } = ReactDOM;

class Parent extends Component {

render() {

return (

{ this.child = instance; }} />

{ this.child.getAlert(); }}>Click

);

}

}

class Child extends Component {

getAlert() {

alert('clicked');

}

render() {

return (

Hello

);

}

}

render(

,

document.getElementById('app')

);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值