我正在尝试在 react 导航标题中的自定义按钮内调用自定义函数。我已经研究了几种方法来做到这一点,我发现的最好结果是使函数静态,即:
export class MyClass extends React.Component{
static navigationOptions = ({navigation}) => ({
headerRight: (<Button title='press me' onPress={()=> MyClass.SomeFunction() } ></Button>)
});
static SomeFunction(){
/*Some code here*/
}
/*Some extra code here*/
}
但是,我的问题是,我需要访问 SomeFunction()
中的一些状态属性,并且您可能知道,您无法在静态函数中访问 this
。
有什么方法可以访问静态中组件的状态,或者有没有更好的方法可以在标题中的按钮中实现自定义功能???
最佳答案
作为替代解决方案,您可以设置导航器状态来设置和获取值。
如果您使用 AppWithNavigation 状态父级作为导航结构的根,则应该将 navigation
属性传递给子元素,如下所示:
render() {
const { dispatch, nav, } = this.props
return (
<AppNavigator
navigation={addNavigationHelpers({
dispatch: dispatch,
state: nav,
})}
/>
)
}
如果是这样,只需使用以下行设置您的值:
this.props.navigation.setParams({someValue: 'Value'})
然后随时获取您的设置值,如下所示:
this.props.navigation.state.someValue
或者
const { someValue } = this.props.navigation.state
但请记住,首次渲染时组件状态可能为 null 或未定义。因此,在尝试获取之前,您需要检查其是否存在:
if (!this.props.navigation.state) {
return null
}
const someValue = this.navigation.state.someValue
if (someValue) {
/* you can use your someValue here! */
}
请注意每条路线都有自己的状态对象。当屏幕更改时,this.props.navigation.state
对象的状态也会更改。我认为,如果您需要一个全局解决方案,您可能会使用 Redux。
关于javascript - 标题按钮内的自定义功能 react native ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47862586/