gpt4 book ai didi

javascript - 将方法作为 prop 传递给类静态函数

转载 作者:行者123 更新时间:2023-12-01 00:23:29 25 4
gpt4 key购买 nike

我自己无法解决这个问题。我有一个类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com