[英]React Native - Init Dependency Component
I have two components我有两个组件
I want to initialise ChatScreen
inside VideoSessionScreen
component and render it when required.我想在
VideoSessionScreen
组件中初始化ChatScreen
并在需要时呈现它。
I am able to render it by using <ChatScreen/>
inside the render of VideoSessionScreen
.我可以通过在
VideoSessionScreen
的渲染中使用<ChatScreen/>
来渲染它。
My problem is, chat screen has componentDidMount
which has code to fetch data from server.我的问题是,聊天屏幕有
componentDidMount
,它有从服务器获取数据的代码。 I want to fire componentDidMount
of ChatScreen only once in VideoSessionScreen
, however currently it keeps triggering componentDidMount
of ChatScreen
every-time it re-renders VideoSessionScreen
(because is places in conditional render method inside VideoSessionScreen
), find below sample code on render()
in VideoSessionScreen
for reference我想火
componentDidMount
ChatScreen的只有一次VideoSessionScreen
,但是目前它保持触发componentDidMount
的ChatScreen
的每次它重新呈现VideoSessionScreen
(因为是在有条件的地方呈现内法VideoSessionScreen
),找到下面的示例代码render()
在VideoSessionScreen
以供参考
render() {
return(
{'video' === this.state.displayScreen &&
<VideoScreen/>
}
{'chat' === this.state.displayScreen &&
<ChatScreen/>
}
);
}
My question is, How do I initialise <ChatScreen>
and hide/show (toggle) the component.我的问题是,如何初始化
<ChatScreen>
并隐藏/显示(切换)组件。
I tried storing in constant, state etc. none works.我尝试存储在常量、状态等中。没有任何效果。
Thanks.谢谢。
You have a few options:您有几个选择:
1) Don't fetch the data on the ChatScreen component. 1) 不要在 ChatScreen 组件上获取数据。 Use Redux or fetch it on the main component and pass it down.
使用 Redux 或在主组件上获取它并向下传递。
2) Instead of doing a conditional render, display both screens but set the opacity of the visible one to 1 and of the invisible one to 0. Also use pointerEvents="none" for the invisible screen. 2) 不进行条件渲染,而是同时显示两个屏幕,但将可见的不透明度设置为 1,将不可见的不透明度设置为 0。对于不可见的屏幕也使用 pointerEvents="none"。
3) Do the same as in 2 but use animations. 3) 与 2 相同,但使用动画。 In shouldComponentUpdate, return false so that the component is not rerendered.
在 shouldComponentUpdate 中,返回 false 以便组件不会被重新渲染。
Inside of the render() method:在 render() 方法内部:
render() {
const { displayScreen } = this.props;
return (
<VideoScreen opacity={'video' === displayScreen ? 1 : 0} pointerEvents={'video' === displayScreen ? 'auto' : 'none'} />
<ChatScreen opacity={'chat' === displayScreen ? 1 : 0} pointerEvents={'chat' === displayScreen ? 'auto' : 'none'} />
);
}
In your View components in VideoScreen and ChatScreen, do this:在 VideoScreen 和 ChatScreen 的视图组件中,执行以下操作:
render() {
const { opacity, pointerEvents } = this.props;
return (
<View style={{ opacity }} pointerEvents={pointerEvents} />
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.