【发布时间】:2018-09-19 17:02:33
【问题描述】:
我正在通过主渲染函数中的状态和 switch 语句控制应在我的应用程序屏幕上显示的组件。我正在用 react-native 写这个,但这是一个反应结构问题。
我还有一个 Navbar 组件,理想情况下,我希望仅在用户单击 Navbar 本身中的链接时重新呈现,但我不知道如何使用 switch 语句设置来做到这一点的好方法现在,似乎我每次都必须根据状态满足的条件重新渲染导航栏。
我的问题是,有没有办法我仍然可以在渲染方法中使用条件渲染组件,就像我在下面一样,并且有一个组件总是像导航栏一样呈现在屏幕顶部?我知道这对于 React Router 之类的东西是可能的,但是有没有更好的方法来构建它而不使用像 React Router 这样的工具或每次都重新渲染 NavBar 组件?
import React from 'react';
import GPS from './GPS/gps';
import Home from './Home';
import Photo from './Camera/Photo';
export default class App extends React.Component {
constructor() {
super();
this.state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
currentView: null,
currentImage: null,
navigation: 'Overview'
};
this.updateNavigation = this.updateNavigation.bind(this);
}
updateNavigation(view) { //Update view function
this.setState({currentView: view});
}
render() {
const { currentView } = this.state;
switch(currentView) {
case null:
return (
<Home updateNav={this.updateNavigation} />
);
break;
case 'GPS':
return (
<View>
<GPS />
<Text onPress={() => this.setState({currentView: null})}>Back</Text>
</View>
);
break;
case 'Camera':
return (
<Photo updateNav={this.updateNavigation} />
);
break;
case 'viewPicture':
return (
<View>
<Image source={{uri: this.state.currentImage.uri}} style={{width: this.state.currentImage.width/10, height: this.state.currentImage.height/12}} />
</View>
);
break;
}
}
}
【问题讨论】:
标签: javascript reactjs react-native