【问题标题】:React Native - Call Parent ref function from ChildReact Native - 从 Child 调用 Parent ref 函数
【发布时间】:2018-11-27 13:07:31
【问题描述】:

我有一个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;

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

提前致谢!

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    对于像这样最简单的用例,您可以使用回调函数并将其作为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 属性作为函数传递:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 2014-05-02
      • 2020-09-09
      • 2016-03-22
      • 2016-12-26
      相关资源
      最近更新 更多