我在应用程序中使用了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?因此,我可以在其他组件/页面上执行类似图层开/关的操作。
答案 0 :(得分:2)
更新:
使用将起作用的全局变量。
ref={ref=>{
global.input=ref;
}}
此屏幕之后,您现在可以在应用中的任何地方使用global.input.focus()
。
以下是实现此目的的示例:https://snack.expo.io/ryJk3hFKN
您可以创建一个返回该组件的引用的函数。
并将该功能作为道具传递给其他组件
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,
},
});
答案 1 :(得分:0)
尝试将它作为道具传递给要在其中使用引用的组件。例如。
<SecondComponent refOfFirstComponent = this.refs.oMap/>
并在SecondComponent中像这样在任何地方使用它:
this.props.refOfFirstComponent.doSomething();