Reputation: 237
I can't solve this issue by myself. I have a Class
class WebViewScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
url: 'https://example.org',
};
}
someMethod = () => {
return 'something';
}
render() {
return (
<View style={styles.mainContainer}>
<WebView
source={{uri: this.state.url}}
/>
<StatusBar backgroundColor="white" barStyle="dark-content" />
</View>
);
}
static navigationOptions = ({navigation}) => {
return {
headerTitle: () => (
<AddressBar navigation={navigation} />
),
};
};
}
I want to access someMethod
from static navigationOptions
run this.someMethod()
run WebViewScreen.someMethod()
let _this
outside a class, then _this = this
from a WebViewScreen Class constructor
then _this.someMethod()
from static navigationOptions
My question is, how can I achieve this?
Upvotes: 1
Views: 1243
Reputation: 849
There is a build-in function in React Navigation 4 called: setParams. This function could be used to set params in static navigationOptions, however in React Navigation 5 there will be a dynamic way to change the navigation. Until then you should use setParams
. In your WebViewScreen component you should use it like this.
class WebViewScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
url: 'https://example.org'
};
}
componentDidMount() {
const { navigation } = this.props;
navigation.setParams({ logOut: this.someMethod });
}
someMethod = () => {
return 'log out';
};
render() {
return (
<View style={styles.mainContainer}>
<WebView source={{ uri: this.state.url }} />
<StatusBar backgroundColor="white" barStyle="dark-content" />
</View>
);
}
static navigationOptions = ({
navigation,
navigation: {
state: { params }
}
}) => {
return {
headerTitle: () => <AddressBar navigation={navigation} />,
headerRight: (
<TouchableOpacity onPress={() => params.someMethod()}>
Log out
</TouchableOpacity>
)
};
};
}
Important to note: you can only add params to the static nav, when the component is mounted!
Upvotes: 1
Reputation: 36989
You cannot access the component's state from within a static method. What you can do is keeping a navigation's parameter in sync with your local state and/or pass functions to it with
this.props.navigation.setParams({
someMethod: this.someMethod.bind(this)
})
which you can retrieve with:
static navigationOptions = ({ navigation }) => {
const someMethod = navigation.getParam('someMethod', () => null)
// ... someMethod()
Upvotes: 1