Call child function from parent component in React Native

前端 未结 5 455
梦毁少年i
梦毁少年i 2020-12-03 09:47

I\'m developing my first React Native app. What I\'m trying to achieve is to execute a child function from the parent component, this is the situation:

Child

5条回答
  •  生来不讨喜
    2020-12-03 10:08

    Simple and easy way to Parent --> Child function call

    /* 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 (
          
    (this.child = ref)} /> Child
    ); } } /* 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 Hello World!; } }

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

提交回复
热议问题