我有这样的结构,其具有滚动型,这是用5名儿童的父
父组件与滚动型
- COMPONENT1
- COMPONENT2
- Component3
- Component4
- Component5
里面Component3我有一个按钮,按下时应该滚动父组件滚动型到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,如何父滚动任何想法? 我试图找出什么,我缺少的,因为这就是我这个第一次接触。
我所做的是..
在component5我在主视图中调用onLayout然后保存x
和y
在父组件。 滚动到它的分量3单击我调用使用父功能的滚动视图裁判滚动到之前存储的值
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>
)
}
}
文章来源: React Native ScrollView - How to scroll to a child component from another child component button?