我试图根据同一组件中处于状态的一个参数来修改我的自定义 header 。但我发现它不起作用。我可以在渲染中执行相同的操作,显然可以,但我如何在 header 中执行此操作?
例如,在本例中,如果 itemNumber > 0
,我想将按钮更改为另一个按钮
...
static navigationOptions = ({ navigation }) => {
return{
title: "Edit Group"+' ',
headerStyle: {
backgroundColor: '#2ca089',
elevation: 0,
shadowOpacity: 0,
borderBottomWidth: 0,
},
headerTintColor: '#fff',
headerRight: (
<Button hasText transparent onPress={() =>
Alert.alert(
"Delete Group",
"Are you sure you want to delete this group? It is a non-reversible action!",
[
{text: 'Yes', onPress: () => console.log('Yes Pressed')},
{text: 'No', onPress: () => console.log('No Pressed'), style: 'cancel'},
],
)
}>
<Text>Delete Group</Text>
</Button>
),
};
}
constructor(props) {
super(props)
this.state = {
dataSource : [],
text : '',
itemNumber : 0,
}
}
...
我知道,因为它是一个静态组件,所以不会动态修改,但我不知道如何以另一种方式做到这一点。
谢谢
最佳答案
我看不到 TNC 的答案在哪里实现 headerRight
内的回调函数,以便重新更新导航标题,我认为这是问题所在。
我的解决方案如下:
The variable which you want to observe is itemNumber, make sure is in the constructor ✅
constructor(props) {
super(props)
this.state = {
dataSource : [],
text : '',
itemNumber : 0,
selectedItems: []
}
}
Then, inside the function which you trigger the event which requires the update for the header add the following code:
triggerFunction = parameters => {
//...
let newValue = 1 //Implement your logic
this.setState(({itemNumber}) => {
this.props.navigation.setParams({itemNumber: newValue})
return {itemNumber: newValue }
});
//...
};
To conclude, on the navigationOption add the following code:
static navigationOptions = ({ navigation }) => {
return{
headerRight:
navigation.getParam('itemNumber', 0) > 0
?
<Button hasText transparent onPress={() =>
Alert.alert(
"Delete User",
"Are you sure you want to delete this user/users? It is a non-reversible action!",
[
{text: 'Yes', onPress: () => console.log('Yes Pressed')},
{text: 'No', onPress: () => console.log('No Pressed'), style: 'cancel'},
],
)
}>
<Text>Delete Users</Text>
</Button>
:
null
};
}
我从这个答案中得到了启发:
https://stackoverflow.com/a/51911736/5288983
我还附上了文档,您可以在其中更好地理解该方法:
https://reactnavigation.org/docs/en/headers.html#setting-the-header-title
关于react-native - 根据一个参数修改header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56853001/