0

我目前正在使用react native modal,它的目的是显示模态。

我目前的问题是我想展示模态应用程序。例如,当收到推送通知时,无论用户在哪个屏幕中,我都想调用模式。模式的当前设计将其绑定到单个屏幕。

如何克服?

4

1 回答 1

0

首先为您的模态创建一个上下文

const BottomModal = React.createContext();

然后使用 reactcontext 提供程序提供您的模式




export const BottomModalProvider = ({children}) => {
  const panelRef = useRef();
  const _show = useCallback((data, type) => {
    panelRef.current.show();
  }, []);

  const _hide = useCallback(() => {
    panelRef.current.hide();
  }, []);



  const value = useMemo(() => {
    return {
      _show,
      _hide,
    };
  }, [_hide, _show]);

  return (
    <BottomPanelContext.Provider value={value}>
      {children}
      <BottomPanel fixed ref={panelRef} />
    </BottomPanelContext.Provider>
  );
};

这是底部面板的代码


function BottomPanel(props, ref) {
  const {fixed} = props;
  const [visible, setVisibility] = useState(false);

  const _hide = () => {
    !fixed && hideModal();
  };

  const hideModal = () => {
    setVisibility(false);
  };

  useImperativeHandle(ref, () => ({
    show: () => {
      setVisibility(true);
    },
    hide: () => {
      hideModal();
    },
  }));

  return (
    <Modal
      // swipeDirection={["down"]}
      hideModalContentWhileAnimating
      isVisible={visible}
      avoidKeyboard={true}
      swipeThreshold={100}
      onSwipeComplete={() => _hide()}
      onBackButtonPress={() => _hide()}
      useNativeDriver={true}
      style={{
        justifyContent: 'flex-end',
        margin: 0,
      }}>
      <Container style={[{flex: 0.9}]}>
        {!fixed ? (
          <View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
            <Button
              style={{marginBottom: 10}}
              color={'white'}
              onPress={() => setVisibility(false)}>
              OK
            </Button>
          </View>
        ) : null}
        {props.renderContent && props.renderContent()}
      </Container>
    </Modal>
  );
}

BottomPanel = forwardRef(BottomPanel);

export default BottomPanel;


然后使用提供程序包装您的应用程序

...
  <BottomModalProvider>
          <NavigationContainer screenProps={screenProps} theme={theme} />
  </BottomModalProvider>
...

最后如何显示或隐藏模态提供自定义钩子

const useBottomPanel = props => {
  return useContext(BottomPanelContext);
};

在应用程序的任何地方使用它


  const {_show, _hide} = useBottomModal();
   //....
   openModal=()=> {
     _show(); 
   }
  //...

如果您不使用钩子或使用类组件,您可以轻松地将钩子与类上下文转换

https://reactjs.org/docs/context.html#reactcreatecontext

通过这种方式,您可以实现仅从组件内显示模态另一种方法是将面板引用全局存储在任何地方,并使用该引用来显示对非组件文件(如 redux 或通知案例)的隐藏。

于 2020-03-18T07:25:41.233 回答