第二天使用 React Native,所以我不知道自己在做什么,但如何使用 react-native-scrollable-tab-view 从另一个组件切换标签页?
https://github.com/skv-headless/react-native-scrollable-tab-view
我在 ButtonPage 中有一个 MenuButton,我正在尝试使用 onPress 切换选项卡。然而,当我点击它时,我得到:
undefined is not an object (evaluating 'this.props.tabView.goToPage')
我得到的是这个
export default class Home extends Component {
render() {
return (
<View style={{flex: 1}}>
<StatusBar
barStyle='light-content'/>
<ScrollableTabView initialPage={1} renderTabBar={false}
ref={(tabView) => { this.tabView = tabView}}>
<FriendsPage tabView={this.tabView} tabLabel="Friends" />
<ButtonPage tabView={this.tabView} tabLabel="Button" />
<HangoutsPage tabView={this.tabView} tabLabel="Hangouts" />
</ScrollableTabView>
</View>
)
}
}
在我的 ButtonPage 中我有这个
export default class ButtonPage extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.buttonsContainer}>
<HangoutsButton/>
<View style={styles.spacer}/>
<MenuButton/>
</View>
</View>)
}
}
MenuButton 就是这样描述的
export default class MenuButton extends Component {
constructor(props) {
super(props)
this.goToPage = this.goToPage.bind(this)
}
goToPage(pageNumber) {
this.props.tabView.goToPage(pageNumber)
}
render() {
return (
<Indicator
position='left top'
value='3'
type='warning'>
<TouchableHighlight
onPress={() => this.goToPage(0)}
underlayColor='#ed8600'
style={styles.touchable}>
<Image source={require('./resources/menuicon.png')} style={styles.image} />
</TouchableHighlight>
</Indicator>
)
}
}
如何获取我的 scrollableTabView 一直到我的按钮的引用,以便我可以点击它并使用 goToPage 更改页面?
我假设您可以将对象粘贴到 Prop 中,然后将该 Prop 一直向下传递,然后从 MenuButton 对其使用函数 goToPage。
最佳答案
您不需要一直向下浏览 tabview ref。只需使用
export default class MenuButton extends Component {
render() {
return (
<Indicator
position='left top'
value='3'
type='warning'>
<TouchableHighlight
onPress={() => this.props.onPress && this.props.onPress()}
underlayColor='#ed8600'
style={styles.touchable}>
<Image source={require('./resources/menuicon.png')} style={styles.image} />
</TouchableHighlight>
</Indicator>
)
}}
export default class ButtonPage extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.buttonsContainer}>
<HangoutsButton/>
<View style={styles.spacer}/>
<MenuButton onPress={ () => this.props.goToPage && this.props.goToPage() }/>
</View>
</View>)
}}
最后
export default class Home extends Component {
goToPage(pageId) {
this.tabView.goToPage(pageId);
}
render() {
return (
<View style={{flex: 1}}>
<StatusBar
barStyle='light-content'/>
<ScrollableTabView initialPage={1} renderTabBar={false}
ref={(tabView) => { this.tabView = tabView}}>
<FriendsPage tabView={this.tabView} tabLabel="Friends" />
<ButtonPage tabView={this.tabView} tabLabel="Button" goToPage={ () => this.goToPage(1) } />
<HangoutsPage tabView={this.tabView} tabLabel="Hangouts" />
</ScrollableTabView>
</View>
)
}
}
关于javascript - 如何使用 react-native-scrollable-tab-view 从另一个组件切换标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42752567/