最后,我终于做到了.我不知道它会带来什么性能问题,但它们不应该是一个问题,因为它只在调整大小或方向改变时才会被调用.
我制作了一个全局控制器,其中有一个函数接收组件(容器、视图),并向其中添加一个事件侦听器:
const getScreenInfo = () => {
const dim = Dimensions.get('window');
return dim;
}
const bindScreenDimensionsUpdate = (component) => {
Dimensions.addEventListener('change', () => {
try{
component.setState({
orientation: isPortrait() ? 'portrait' : 'landscape',
screenWidth: getScreenInfo().width,
screenHeight: getScreenInfo().height
});
}catch(e){
// Fail silently
}
});
}
这样,当方向或窗口大小发生变化时,我将强制重新渲染组件.
然后,在每个组件构造函数上:
import ScreenMetrics from './globalFunctionContainer';
export default class UserList extends Component {
constructor(props){
super(props);
this.state = {};
ScreenMetrics.bindScreenDimensionsUpdate(this);
}
}
这样,每当窗口调整大小或方向改变时,它都会被重新命名.
You should note,然而,这必须应用到我们想要监听方向变化的每个组件,因为如果父容器被更新,但是state
(或props
)个子容器没有更新,它们将不会被重新命名,所以it can be a performance kill如果我们有一个大的子树监听它.
希望它能帮助别人!