在本节中,我们将学习如何在标题栏添加右上角按钮,并实现编辑状态的切换。以下是实现步骤:
一、添加编辑按钮
1. 安装 react-navigation-header-buttons
yarn add react-navigation-header-buttons
2. 配置编辑按钮
在 pages/Category/HeaderRightBtn.tsx 中实现编辑按钮:
import React from 'react';
import { HeaderButtons, Item } from 'react-navigation-header-buttons';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { connect, ConnectedProps } from 'react-redux';
import { RootState } from '@/models/index';
import { CategoryModelType } from '@/models/category';
interface IProps extends ConnectedProps<typeof connector> {}
const mapStateToProps = ({ category }: RootState) => ({
isEdit: category.isEdit,
});
const connector = connect(mapStateToProps);
class HeaderRightBtn extends React.Component<IProps> {
onPress = () => {
const { dispatch, isEdit } = this.props;
dispatch({
type: 'category/toggle',
});
};
render() {
const { isEdit } = this.props;
return (
<HeaderButtons>
<Item
title={isEdit ? '完成' : '编辑'}
onPress={this.onPress}
style={styles.item}
/>
</HeaderButtons>
);
}
}
const styles = StyleSheet.create({
item: {
padding: 10,
},
});
export default connector(HeaderRightBtn);
3. 更新分类页面
在 pages/Category/index.tsx 中设置导航栏按钮:
import HeaderRightBtn from './HeaderRightBtn';
class Category extends Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
myCategorys: this.props.myCategorys,
};
props.navigation.setOptions({
headerRight: () => <HeaderRightBtn />,
});
}
componentWillReceiveProps(nextProps: IProps) {
if (nextProps.myCategorys !== this.props.myCategorys) {
this.setState({
myCategorys: nextProps.myCategorys,
});
}
}
render() {
// ...
}
}
二、切换编辑状态
1. 更新分类模块的 Model
在 models/category.ts 中添加 isEdit 状态和 toggle 方法:
export interface CategoryModelState {
isEdit: boolean;
categorys: ICategory[];
myCategorys: ICategory[];
}
export interface CategoryModelType extends Model {
effects: {
toggle: Effect;
};
}
const categoryModel: CategoryModelType = {
namespace: 'category',
state: {
isEdit: false,
categorys: [],
myCategorys: [],
},
effects: {
*toggle(action, { put, select }) {
const category: CategoryModelState = yield select((state: RootState) => state.category);
yield put({
type: 'setState',
payload: {
isEdit: !category.isEdit,
},
});
},
},
};
2. 更新导航器的样式
在 navigator/index.tsx 中设置标题栏的样式:
<Stack.Navigator
headerMode="float"
screenOptions={{
headerTintColor: '#333',
headerBackTitleVisible: false,
}}
/>
三、适配设备平台
处理标题栏高度的适配问题:
import { Platform, StatusBar } from 'react-native';
const headerStyle = {
...Platform.select({
android: {
headerStatusBarHeight: StatusBar.currentHeight,
},
}),
};
四、总结
在本节中,我们完成了标题栏右上角按钮的添加和编辑状态的切换功能。通过使用 react-navigation-header-buttons 库,我们能够更方便地创建导航栏按钮,并动态修改其文本内容。下一节,我们将学习如何实现分类的添加和删除功能。