如何在 React Native 的另一个组件中使用 ref?
How to use ref in another component in react native?
我在我的应用程序中使用了 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?所以我可以从其他 component/page 做一些类似层 on/off 的事情。
尝试将其作为 prop 传递给要在其中使用 refs 的组件。例如
<SecondComponent refOfFirstComponent = this.refs.oMap/>
并在 SecondComponent 中像这样在任何地方使用它:
this.props.refOfFirstComponent.doSomething();
更新:
使用有效的全局变量。
ref={ref=>{
global.input=ref;
}}
现在您可以在该屏幕后的应用中的任何地方使用 global.input.focus()
。
这里有一个实现这个的例子:https://snack.expo.io/ryJk3hFKN
您可以创建一个 returns 引用该组件的函数。
并将该函数作为道具传递给其他组件
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,
},
});
我在我的应用程序中使用了 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?所以我可以从其他 component/page 做一些类似层 on/off 的事情。
尝试将其作为 prop 传递给要在其中使用 refs 的组件。例如
<SecondComponent refOfFirstComponent = this.refs.oMap/>
并在 SecondComponent 中像这样在任何地方使用它:
this.props.refOfFirstComponent.doSomething();
更新:
使用有效的全局变量。
ref={ref=>{
global.input=ref;
}}
现在您可以在该屏幕后的应用中的任何地方使用 global.input.focus()
。
这里有一个实现这个的例子:https://snack.expo.io/ryJk3hFKN
您可以创建一个 returns 引用该组件的函数。
并将该函数作为道具传递给其他组件
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,
},
});