使用ref从父组件触发子组件功能

时间:2020-05-11 08:23:53

标签: reactjs react-native refs

早上!

我有一个如下所示的组件设置(React Native)

我试图通过按下同级组件中的按钮来触发类<Child>中的函数。在父组件<Parent>中,我为<Child>组件设置了引用。裁判总是null,所以我在这里错过了一些东西,但不确定是什么。

如果我将ref附加到另一个组件上,例如在DOM中处于同一级别的<TouchableOpacity>,则该ref存在吗?我不确定是否是因为我的<Child>函数是否自定义。

使用RN 0.6。


class Parent extends React.Component {

  ...

  fireChildFunction = () => {
    if(!this.childRef) return null;

    this.childRef.childFunction()
  }

  render(){
    return (
      <Parent>
        <Child ref={(ref) => {this.childRef = ref}/>
        <ButtonChild onPress={this.fireChildFunction} />
      </Parent>
    ) 
  }
}
...

class Child extends React.Component {

  childFunction() {
    // do something
  }

  render() {
    return (
      <View>
         ...
      </View>
    ) 
  }

}

任何帮助将不胜感激!

谢谢

2 个答案:

答案 0 :(得分:0)

请检查以下示例,其中我们在ref的帮助下调用了同级函数。

父组件

import React, {useEffect, useState} from 'react';
import Child from "./Child";
import Sibling from "./Sibling";

export default class Parent extends React.Component{
    constructor(props){
        super(props);
        this.childRef = React.createRef();
    }

    fireChildFunction = () => {
        alert('called from fireChildFunction');
        if (!this.childRef) return null;
        this.childRef.current.childFunction()
    };

    render()
    {
        return (
            <div>
                <Child ref={this.childRef}/>
                <Sibling onPress={this.fireChildFunction}/>
            </div>
        );
    }
}

子组件

import React, {useEffect, useState} from 'react';

export default class Child extends React.Component {

    childFunction = () =>{
        alert('called from childFunction');
    };

    render() {
        return (
            <div>

            </div>
        );
    }
}

同级组件

import React, {useEffect, useState} from 'react';

export default class Sibling extends React.Component {

    onClick = () => {
        this.props.onPress();
    };

    render() {
        return (
            <div>
                <button onClick={this.onClick}>Click from Sibling</button>
            </div>
        );
    }
}

答案 1 :(得分:0)

我发现了问题。我正在使用Redux,当您使用connect函数时,它将创建一个HOC包装器。因此,未将ref分配给<Child>组件。我必须在包装我的{forwardRef: true}组件的connect函数中添加<Child>作为第四个参数。希望有一天能对某人有所帮助!

供参考: https://itnext.io/advanced-react-redux-techniques-how-to-use-refs-on-connected-components-e27b55c06e34

相关问题