React Native ScrollView - Как перейти к дочернему компоненту с помощью кнопки другого дочернего компонента? - PullRequest
0 голосов
/ 28 февраля 2019

У меня есть эта структура с ScrollView, который является родителем с 5 дочерними элементами

Родительский компонент с ScrollView

  • Компонент1
  • Компонент2
  • Component3
  • Component4
  • Component5

Внутри 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>
        );
    }
};

А Комментарии - это Компонент5, есть идеи, как сделать родительскую прокрутку?Я пытаюсь понять, чего мне не хватает, так как это мой первый контакт с этим.

1 Ответ

0 голосов
/ 28 февраля 2019

То, что я сделал, было ..
в component5 Я вызываю onLayout в главном окне, а затем сохраняю x и y в родительском компоненте.Чтобы прокрутить до него в компоненте 3, я вызываю родительскую функцию, которая использует ссылку scrollview для прокрутки до значений, сохраненных до

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>
        )
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...