从React Native中的父组件调用子函数

Pot*_*neo 28 react-native

我正在开发我的第一个React Native应用程序.我想要实现的是从父组件执行子函数,这是这样的情况:

儿童

export default class Child extends Component {
  ...
  myfunct: function() {
    console.log('Managed!');
  }
  ...
  render(){
    return(
      <Listview
      ...
      />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

export default class Parent extends Component {
  ...
  execChildFunct: function() {
    ...
    //launch child function "myfunct"
    ...
    //do other stuff
  }

  render(){
    return(
      <View>
        <Button onPress={this.execChildFunct} />
        <Child {...this.props} />
      </View>);
  }
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,'Managed!'当我按下父类中的按钮时,我想记录.它怎么可行?

Ado*_*zis 35

以下是如何使用功能组件来做到这一点:

家长

  1. 用于useRef()在父组件中为子组件提供引用:
const childRef = useRef()
// ...
return (
   <ChildComponent ref={childRef} />
)
...
Run Code Online (Sandbox Code Playgroud)

孩子

  1. ref作为构造函数参数之一传递:
const ChildComponent = (props, ref) => {
  // ...
}
Run Code Online (Sandbox Code Playgroud)
  1. 从库中导入useImperativeHandleforwardRef方法'react'
import React, { useImperativeHandle, forwardRef } from 'react'
Run Code Online (Sandbox Code Playgroud)
  1. 用于useImperativeHandle将函数绑定到ref对象,这将使父级可以访问这些函数

这些方法在内部不可用,因此您可能想使用它们来调用内部方法。

const ChildComponent = (props, ref) => {
  //...
  useImperativeHandle(ref, () => ({
    // each key is connected to `ref` as a method name
    // they can execute code directly, or call a local method
    method1: () => { localMethod1() },
    method2: () => { console.log("Remote method 2 executed") }
  }))
  //...
  
  // These are local methods, they are not seen by `ref`,
  const localMethod1 = () => {
    console.log("Method 1 executed")
  }
  // ..
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用以下命令导出子组件forwardRef
const ChildComponent = (props, ref) => {
  // ...
}
export default forwardRef(ChildComponent)
Run Code Online (Sandbox Code Playgroud)

把它们放在一起

子组件

import React, { useImperativeHandle, forwardRef } from 'react';
import { View } from 'react-native'


const ChildComponent = (props, ref) => {
  useImperativeHandle(ref, () => ({
    // methods connected to `ref`
    sayHi: () => { sayHi() }
  }))
  // internal method
  const sayHi = () => {
    console.log("Hello")
  }
  return (
    <View />
  );
}

export default forwardRef(ChildComponent)

Run Code Online (Sandbox Code Playgroud)

父组件

import React, { useRef } from 'react';
import { Button, View } from 'react-native';
import ChildComponent from './components/ChildComponent';

const App = () => {
  const childRef = useRef()
  return (
    <View>
      <ChildComponent ref={childRef} />
      <Button
        onPress={() => {
          childRef.current.sayHi()
        }}
        title="Execute Child Method"
      />
    </View>
  )
}

export default App
Run Code Online (Sandbox Code Playgroud)

Expo Snacks 上有一个交互式演示: https ://snack.expo.dev/@backupbrain/calling-functions-from-other-components

这个解释是根据这篇TutorialsPoint文章修改的


Nad*_*bit 24

您可以为子组件添加引用:

<Child ref='child' {...this.props} />
Run Code Online (Sandbox Code Playgroud)

然后像这样调用孩子的方法:

<Button onPress={this.refs.child.myfunc} />
Run Code Online (Sandbox Code Playgroud)


Inc*_*tor 22

Nader Dabit的答案已经过时,因为不推荐在ref属性中使用String文字.这就是我们2017年9月的表现:

<Child ref={child => {this.child = child}} {...this.props} />
<Button onPress={this.child.myfunc} />
Run Code Online (Sandbox Code Playgroud)

相同的功能,但我们不是使用String来引用组件,而是将其存储在全局变量中.

  • 我必须感谢你,我不知道为什么这个答案不被接受,这是目前的做法。我刚刚在学习 react native,所以代码有点混乱。我也不得不对其进行一些更改才能使其正常工作。&lt;Child ref={ (child) =&gt; { this.child = child; }}/&gt; 并调用它使用 this.child.functionName (2认同)

Ash*_*k R 8

它在反应。希望对您有帮助。

class Child extends React.Component {
  componentDidMount() {
    this.props.onRef(this)
  }
  componentWillUnmount() {
    this.props.onRef(null)
  }
  method() {
    console.log('do stuff')
  }
  render() {
    return <h1>Hello World!</h1>
  }
}
Run Code Online (Sandbox Code Playgroud)
class EnhancedChild extends React.Component {
        render() {
        return <Child {...this.props} />
      }
    }

class Parent extends React.Component {
  onClick = () => {
    this.child.method() // do stuff
  };
  render() {
    return (
      <div>
        <EnhancedChild onRef={ref => (this.child = ref)} />
        <button onClick={this.onClick}>Child.method()</button>
      </div>
    );
  }
}

ReactDOM.render(<Parent />, document.getElementById('root'))
Run Code Online (Sandbox Code Playgroud)

原始解决方案:

https://jsfiddle.net/frenzzy/z9c46qtv/

https://github.com/kriasoft/react-starter-kit/issues/909


Him*_*dia 7

简单易用的方法父-->子函数调用

/* Parent.js */
import React, { Component } from "react";
import { TouchableOpacity, Text } from "react-native";
import Child from "./Child";

class Parent extends React.Component {
  onChildClick = () => {
    this.child.childFunction(); // do stuff
  };
  render() {
    return (
      <div>
        <Child onRef={(ref) => (this.child = ref)} />
        <TouchableOpacity onClick={this.onChildClick}>
          <Text>Child</Text>
        </TouchableOpacity>
      </div>
    );
  }
}

/* Child.js */
import React, { Component } from "react";

class Child extends React.Component {
  componentDidMount() {
    this.props.onRef(this);
  }
  componentWillUnmount() {
    this.props.onRef(undefined);
  }
  childFunction() {
    // do stuff
    alert("childFunction called");
  }
  render() {
    return <View>Hello World!</View>;
  }
}
Run Code Online (Sandbox Code Playgroud)

原始解决方案: https://github.com/kriasoft/react-starter-kit/issues/909