我通过主渲染函数中的状态和 switch 语句控制应该在我的应用程序屏幕上显示的组件。我正在用 react-native 写这篇文章,但这是一个 react 结构问题。
我还有一个 Navbar 组件,理想情况下,我希望仅在用户单击 Navbar 本身中的链接时才重新呈现,但我不知道如何使用 switch 语句设置来执行此操作现在,我似乎每次都必须根据状态满足的条件重新呈现 Navbar。
我的问题是,有没有一种方法我仍然可以在渲染方法中使用组件的条件渲染,就像我在下面一样,并且有一个组件总是像导航栏一样渲染在屏幕的顶部?我知道这可以通过 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;
}
}
}
最佳答案
始终保持渲染尽可能干净。
您可以使用 && 运算符来做同样的事情,而不是使用 switch case。使用 && 运算符并检查每个案例并相应地呈现。检查下面的代码以便更好地理解。
render() {
const { currentView } = this.state;
return(
{currentView == null && (
<Home updateNav={this.updateNavigation} />
)}
{currentView == "GPS" && (
<View>
<GPS />
<Text onPress={() => this.setState({currentView: null})}>Back</Text>
</View>
)}
{currentView == "Camera" && (
<View>
<Photo updateNav={this.updateNavigation} />
</View>
)}
{currentView == "viewPicture" && (
<View>
<Image source={{uri: this.state.currentImage.uri}} style={{width: this.state.currentImage.width/10, height: this.state.currentImage.height/12}} />
</View>
)}
)
}
关于javascript - React 条件渲染和导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52410913/