【问题标题】:How to use ref in another component in react native?如何在反应原生的另一个组件中使用 ref?
【发布时间】:2019-04-09 06:13:06
【问题描述】:

我在我的应用程序中使用了 react native mpaboxgl。

import MapboxGL from "@mapbox/react-native-mapbox-gl";


<MapboxGL.MapView
  logoEnabled={false}
  attributionEnabled={false}
  ref={(e) => { this.oMap = e }}
  zoomLevel={6}
  centerCoordinate={[54.0, 24.0]}> 
<MapboxGL.MapView> 

如何在另一个组件中使用oMap?所以我可以做一些事情,比如从其他组件/页面打开/关闭图层。

【问题讨论】:

    标签: reactjs react-native react-native-maps


    【解决方案1】:

    更新

    使用一个可以工作的全局变量。

    ref={ref=>{
       global.input=ref;
       }}
    

    现在您可以在此屏幕之后的应用中的任何位置使用global.input.focus()


    这里有一个例子来实现这一点:https://snack.expo.io/ryJk3hFKN

    您可以创建一个返回该组件的 ref 的函数。
    并将该函数作为道具传递给其他组件

    import * as React from 'react';
    import { Text, View, StyleSheet, TextInput, TouchableOpacity } from 'react-native';
    
    export default class App extends React.Component {
      getInputRef = () => this.input;
    
      render() {
        return (
          <View style={styles.container}>
            <TextInput
              ref={ref => {
                this.input = ref;
              }}
              placeholder="Hi there"
            />
            <SecondComp getInputRef={this.getInputRef} />
          </View>
        );
      }
    }
    
    class SecondComp extends React.Component {
      render() {
        return (
          <TouchableOpacity
            onPress={() => {
              this.props.getInputRef().focus();
            }}>
            <Text>click to Focus TextInput from the other component</Text>
          </TouchableOpacity>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'space-around',
        backgroundColor: '#ecf0f1',
        padding: 8,
      },
    });
    

    【讨论】:

    • 谢谢,但没有父子关系。我想在 sidemenu 中使用,sideme 是内容组件
    • 感谢全局关键字很有帮助。所以现在可以在任何地方访问它。
    【解决方案2】:

    尝试将其作为道具传递给您要在其中使用 refs 的组件。例如。

    <SecondComponent refOfFirstComponent = this.refs.oMap/>
    

    并在 SecondComponent 中像这样在任何地方使用它:

    this.props.refOfFirstComponent.doSomething();
    

    【讨论】:

    • 当分配 ref 需要时间时,这会产生错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多