Syn*_*nia 6 react-native react-native-scrollview react-native-android react-navigation
当我们刚刚通过StackNavigator导航到当前屏幕时,是否可以告诉ScrollView滚动到特定位置?
我有两个屏幕。菜单和项目。菜单是按钮的列表,每个按钮一个。“项目”屏幕包含一个使用ScrollView构建的轮播,带有图片和每个项目的详细说明。
当我单击“菜单”屏幕中的按钮时,我想导航到“项目”屏幕,然后自动滚动到该按钮代表的项目。
我读到您可以像下面这样使用StackNavigator时传递参数:但是我不知道如何在我的“项目”屏幕中读出该参数。
navigate('Items', { id: '1' })
Run Code Online (Sandbox Code Playgroud)
那么这在React Native中是可能的吗,我该怎么做?还是我使用了错误的导航器?
这是我的两个屏幕的精简版:
App.js:
const SimpleApp = StackNavigator({
Menu: { screen: MenuScreen},
Items: { screen: ItemScreen }
}
);
export default class App extends React.Component {
render() {
return <SimpleApp />;
}
}
Run Code Online (Sandbox Code Playgroud)
Menu.js
export default class Menu extends React.Component {
constructor(props){
super(props)
this.seeDetail = this.seeDetail.bind(this)
}
seeDetail(){
const { navigate } = this.props.navigation;
navigate('Items')
}
render(){
<Button onPress={this.seeDetail} title='1'/>
<Button onPress={this.seeDetail} title='2'/>
}
}
Run Code Online (Sandbox Code Playgroud)
Items.js
export default class Items extends React.Component {
render(){
let scrollItems = [] //Somecode that generates and array of items
return (
<View>
<View style={styles.scrollViewContainer}>
<ScrollView
horizontal
pagingEnabled
ref={(ref) => this.myScroll = ref}>
{scrollItems}
</ScrollView>
</View>
</View>
)
}
}
Run Code Online (Sandbox Code Playgroud)
PS我目前专门针对Android,但理想情况下可能会有跨平台的解决方案。
我读到您可以像下面这样使用StackNavigator时传递参数:但是我不知道如何在我的“项目”屏幕中读出该参数。
这是通过访问this.props.navigation.state.params子组件内部来实现的。
我认为最好scrollTo在您的滚动视图引用上调用它的时间是在第一次分配它时。您已经为它提供了引用并正在运行一个回调函数-我只是对其进行了调整,以便它也可以同时调用scrollTo:
export default class Items extends React.Component {
render(){
let scrollItems = [] //Somecode that generates and array of items
const {id} = this.props.navigation.state.params;
return (
<View>
<View style={styles.scrollViewContainer}>
<ScrollView
horizontal
pagingEnabled
ref={(ref) => {
this.myScroll = ref
this.myScroll.scrollTo() // !!
}>
{scrollItems}
</ScrollView>
</View>
</View>
)
}
}
Run Code Online (Sandbox Code Playgroud)
这就是为什么我使用FlatLists或SectionLists(继承自VirtualizedList)而不是ScrollViews的原因。VirtualizedList具有scrollToIndex函数,该函数更加直观。ScrollView的scrollTo需要x和y参数,这意味着您必须计算要滚动到的确切位置-将每个滚动项目的宽度乘以要滚动到的项目的索引。而且,如果每个项目都涉及填充,则会更加痛苦。
| 归档时间: |
|
| 查看次数: |
10940 次 |
| 最近记录: |