所有可触摸组件(TouchableWithoutFeedback,TouchableOpacity等)都有一个名为
onLongPress的属性.您可以使用此prop来收听长按,然后显示上下文菜单.
为了消除代码混乱并进行大量复制粘贴,您可以将上下文菜单分离为不同的组件,并在长按时将其调用.您还可以使用ActionSheet库来显示所需的选项. React native有一个名为ActionSheetIOS的iOS原生API.如果你在react和react-native上获得更多经验,你可以为此创建一个更好的逻辑,但我将尝试在下面给你一个例子.
// file/that/contains/globally/used/functions.js
const openContextMenu = (event,user,callback) => {
ActionSheetIOS.showActionSheetWithOptions({
options: ['Copy Username','Call User','Add to favorites','Cancel'],cancelButtonIndex: [3],title: 'Hey',message : 'What do you want to do now?'
},(buttonIndexThatSelected) => {
// Do something with result
if(callback && typeof callback === 'function') callback();
});
};
export openContextMenu;
import { openContextMenu } from './file/that/contains/globally/used/functions';
export default class UserCard extends React.Component {
render() {
const { userObject } = this.props;
return(
openContextMenu(event,userObject,() => console.log('Done')}>
openContextMenu(event,() => console.log('Done'))}>
{userObject.name}
);
}
}