代码之家  ›  专栏  ›  技术社区  ›  MoKhajavi75

React Native-从子函数调用父ref函数

  •  0
  • MoKhajavi75  · 技术社区  · 7 年前

    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() 但我怎样才能从法律上澄清这一点呢 小孩 组件?

    提前谢谢!

    1 回复  |  直到 7 年前
        1
  •  2
  •   Anand Undavia    7 年前

    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 onClick 道具作为功能:

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

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

    推荐文章