我自己无法解决这个问题。我有一个类(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} />
),
};
};
}
我想从static navigationOptions
访问someMethod
我尝试了以下方法但没有成功:
运行this.someMethod()
运行WebViewScreen.someMethod()
let _this
在类之外,然后在 WebViewScreen 类构造函数中 _this = this
然后来自 static navigationOptions
_this.someMethod()
<小时/>
我的问题是,我怎样才能实现这一目标?
最佳答案
您无法从静态方法中访问组件的状态。您可以做的就是保持导航参数与本地状态同步和/或将函数传递给它
this.props.navigation.setParams({
someMethod: this.someMethod.bind(this)
})
您可以通过以下方式检索:
static navigationOptions = ({ navigation }) => {
const someMethod = navigation.getParam('someMethod', () => null)
// ... someMethod()
关于javascript - 将方法作为 prop 传递给类静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59213194/