【发布时间】:2021-01-31 11:31:04
【问题描述】:
我是 React Native 的新手,我正在尝试创建一个带有自定义导航栏的应用,当你点击链接时,它会在页面之间跳转。
这是我的代码的缩写版本:
class App extends Component {
constructor(props) {
super(props);
this.state = {
dicePage: true,
itemsPage: false
}
}
dicePress = () => {
this.setState({
dicePage: true,
itemsPage: false
})
}
itemsPress = () => {
this.setState({
dicePage: false,
itemsPage: true
})
}
render() {
return (
<View style={styles.container}>
<ImageBackground source={backgroundTile} style={styles.bgImage}>
<View style={styles.content}>
<View style={styles.logoContainer}>
<Image source={require('./assets/images/Logo.png')} style={styles.logo} />
</View>
{this.state.dicePage && <DicePage />}
{this.state.itemsPage && <ItemsPage />}
<NavBar value='Dice' dicePress={this.dicePress} itemsPress={this.itemsPress} />
</View>
</ImageBackground>
</View>
);
}
}
export default App;
和
class NavBar extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={styles.bottomNav}>
<TouchableOpacity onPress={this.props.dicePress}>
<Text key='dice' style={styles.nav}>Dice</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.props.itemsPress}>
<Text key='items' style={styles.nav}>Items</Text>
</TouchableOpacity>
</View>
)
}
}
export default NavBar;
所以这在我测试应用程序时有效 - 我将有 4 或 5 个页面,因此需要比三元运算符等更多的选项 - 但我认为可能有更好或更优雅的方法来做到这一点。
我已经尝试过 React Navigator 和其他东西,但我真的在寻找绝对简单的方法来实现这一点(希望使用 DRY 编码,因为重复对我来说感觉不对)。我应该为此映射链接和函数吗?我认为我以前从未映射过函数,并意识到可能应该有一个适用于所有人的自适应函数。
感谢您的建议!
【问题讨论】:
标签: reactjs react-native navigation