如何在 React Native 的另一个组件中使用 ref ?

Khu*_*ari 2 reactjs react-native react-native-maps

我在我的应用程序中使用了 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> 
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*ani 5

更新

使用有效的全局变量。

ref={ref=>{
   global.input=ref;
   }}
Run Code Online (Sandbox Code Playgroud)

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


这是实现此目的的示例:https://snack.expo.io/ryJk3hFKN

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

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,
  },
});
Run Code Online (Sandbox Code Playgroud)