简体   繁体   中英

React Native - Call Parent ref function from Child

I have a Parent component:

import React, { Component } from "react";
import { View, TextInput } from "react-native";

class Parent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      txt: ""
    };
  }

  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <TextInput
          ref={parentInput => {
            this.parentInput = parentInput;
          }}
          style={{
            width: 200,
            height: 100
          }}
          onChangeText={txt => this.setState({ txt })}
          value={this.state.txt}
        />
      </View>
    );
  }
}

export default Parent;

And I have a Child component:

import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";

class Child extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <TouchableOpacity
          style={{
            justifyContent: "center",
            alignItems: "center",
            width: 200,
            height: 100
          }}
          onPress={() => {
            // ???
          }}
        >
          <Text>Clear Input!</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

export default Child;

I know I can clear the parent's input in the Parent using this.parentInput.clear() but how can I clear that from the Child component?

Thanks in advance!

For the most simple use-case like this, you can get around by using a callback function and passing it as a prop .

For example, Child :

<TouchableOpacity
  style={{
    justifyContent: "center",
    alignItems: "center",
    width: 200,
    height: 100
  }}
  onPress={() => {
    this.props.onClick(); // <-- you might want to pass some args as well
  }}
>

And from Parent , when you use child, pass the onClick prop as function:

<Child onClick={() => { 
    console.log('onclick of parent called!');
    this.parentInput.clear(); 
    // Add something more here 
}}>

However, for advanced use case, I recommend using any state management libraries like Redux .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM