我正在使用React Native,它附带了支持 portals的React 16 alpha版本.在浏览器中并且可以访问DOM时,我们可以使用id或类从组件/文件层次结构中的任何位置访问元素,如下所示: const modalRoot = doc
const modalRoot = document.getElementById('modal-root');
并将其传递给createPortal(子容器)容器arg. React docs clearly says比容器应该是DOM元素:
The second argument (container) is a DOM element.
此函数也是ReactDOM的一种方法,它在React Native中不存在.
有没有办法在React Native中实现类似的功能?
使用案例:
我想在我的应用程序的根目录中渲染动画叠加层,但是从树层次结构深层的父级传递动画值道具(不能使用Redux操作来执行此类操作).
我不认为react-native在自己的API中提供此功能.但是有一个库提供类似的功能. react-gateway
根据react-gateway的文档,
It also works in universal (isomorphic) React applications without any additional setup and in React Native applications.
React Gateway does not directly depend on react-dom, so it works fine with React Native under one condition:
You must pass React Native component like View or similar to component prop of .
import React from 'react'; import { Text, View } from 'react-native'; import { Gateway, GatewayDest, GatewayProvider } from 'react-gateway'; export default class Application extends React.Component { render() { return ( <GatewayProvider> <View> <Text>React Gateway Native Example</Text> <View> <Gateway into="one"> <Text>Text rendered elsewhere</Text> </Gateway> </View> <GatewayDest name="one" component={View} /> </View> </GatewayProvider> ); } }
以上示例取自repo本身. react native example