React Native-从Child调用Parent ref函数

时间:2018-11-27 13:07:31

标签: javascript reactjs react-native ecmascript-6

我有一个Parent组件:

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;

我有一个Child组件:

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;

我知道我可以使用Parent清除this.parentInput.clear()中父母的输入,但是如何从Child组件中清除呢?

  

谢谢!

1 个答案:

答案 0 :(得分:2)

对于像这样的最简单的用例,您可以通过使用回调函数并将其作为prop传递来解决。

例如, Child

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

Parent开始,当您使用child时,将onClick prop作为函数传递:

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

但是,对于高级用例,我建议使用任何状态管理库,例如Redux