我有一个带有ScrollView的结构,该视图是一个有5个孩子的父母
具有ScrollView的父组件
在Component3内部,我有一个按钮,当按下该按钮时,应将父组件ScrollView滚动到Component5
类似这样的东西
家庭(父母)
export default class Home extends React.Component {
renderComments() {
return this.state.dataSource.map(item =>
<CommentDetail key={item.id} comment={item} />
);
}
render() {
return (
<ScrollView>
<Component1 />
<Component2 />
<CentralElements {...this.state.dataSource} scroll = {this.props.scroll} />
<Component4 />
<View>
{this.renderComments()}
</View>
</ScrollView>
);
}
}
CentralElements(Component3)
export default class CentralElements extends React.Component {
constructor(props) {
super(props);
}
goToComments= () => {
this.props.scroll.scrollTo({x: ?, y: ?, animated: true});
};
render() {
return (
<ScrollView horizontal={true}>
<TouchableOpacity onPress={this.goToComments}>
<Image source={require('../../assets/image.png')} />
<Text>Comments</Text>
</TouchableOpacity>
...
</TouchableOpacity>
</ScrollView>
);
}
};
注释是Component5,有关如何滚动父级的任何想法? 我试图弄清楚自己所缺少的是什么,因为那是我第一次与之联系。
答案 0 :(得分:0)
我所做的是..
在component5中,我在主视图中调用onLayout,然后将x
和y
保存在父组件中。
要在组件3上单击以滚动到它,请调用父函数,该函数使用scrollview ref滚动到之前存储的值
Component5
export default class Component5 extends Component {
saveLayout() {
this.view.measureInWindow((x, y, width, height) => {
this.props.callParentFunction(x, y)
})
}
render() {
return (
<View ref={ref => this.view = ref} onLayout={() => this.saveLayout()}>
</View>
)
}
}
Component3
export default class Component3 extends Component {
render() {
return (
<View >
<TouchableOpacity onPress={()=>{this.props.goToComponent5()}}>
</TouchableOpacity>
</View>
)
}
}
父母:
export default class Parent extends Component {
constructor(props) {
this.goToComponent5=this.goToComponent5.bind(this)
super(props)
this.state = {
x:0,
y:0,
}
}
callParentFunction(x, y) {
this.setState({ x, y })
}
goToComponent5(){
this.ScrollView.scrollTo({x: this.state.x, y: this.state.y, animated: true});
}
render() {
return (
<View >
<ScrollView ref={ref => this.ScrollView = ref}>
<Component1 />
<Component2 />
<Component3 goToComponent5={this.goToComponent5}/>
<Component4 />
<Component5 callParentFunction={this.callParentFunction}/>
</ScrollView>
</View>
)
}
}