簡體   English   中英

React Native-從Child調用Parent ref函數

[英]React Native - Call Parent ref function from Child

我有一個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組成部分?

提前致謝!

對於這種最簡單的用例,您可以通過使用回調函數並將其作為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM