reactjs - 对 native 搜索使用react并滚动以点击

标签 reactjs typescript react-native react-animated

我需要一些帮助来实现搜索和滚动以在 React Native 中点击。进行了大量搜索并最终陷入了死胡同(找到了一些我无法开始工作的 refs 示例)。

尝试构建此代码段作为启动:

https://snack.expo.io/@norfeldt/searching-and-scroll-to

import React, { Component } from 'react';
import { Text, View, ScrollView, TextInput, StyleSheet } from 'react-native';

export default class App extends Component {

  state = {
    text: '41'
  }

  render() {
    return (
      <View style={styles.container}>

      <TextInput
        style={{height: 60, borderColor: 'gray', borderWidth: 1, borderRadius: 10, margin: 5, padding:30, color: 'black', }}
        onChangeText={(text) => this.setState({text})}
        value={this.state.text}
      />

      <ScrollView >

          {[...Array(100)].map((_, i) => {return <Text style={styles.paragraph} key={i}>{i}</Text>})}

      </ScrollView>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 10,
    backgroundColor: '#ecf0f1',
  },
  paragraph: {
    margin: 10,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: '#34495e',
  },
});

任何入门帮助都将不胜感激。

最佳答案

我的猜测是:

您可以先绑定(bind)一个 ref你的<ScrollView/> .

// ScrollView Ref.
<ScrollView ref={(ref) => this['ScrollView'] = ref}>
  ...
</ScrollView>

还有你的每一个<Text/>组件(作者 index )。

// Text Refs.
<Text ref={(ref) => this[i] = ref} style={styles.paragraph} key={i}>{i}</Text>

然后您可以设置 submit() function .

所述函数可以找到ref等于 this.state.text使用 try catch边缘情况下优雅失败的声明。

如果找到;目标 xy可以使用 measure() 检索偏移量

scrollTo()然后可以调用以滚动到目标组件。

// Scroll To Query.
submit = () => {

  try {

    const { text } = this.state // Text.
    const target = this[text] // Target.

    // Locate Target.
    target.measure((framex, framey, width, height, x, y) => {

      // Scroll To Target.
      this.ScrollView.scrollTo({x, y, animated: true})
    })

  } catch (error) {

    return console.log(error)
  }

}

关于reactjs - 对 native 搜索使用react并滚动以点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47772129/

相关文章:

html - 我可以在 React JS 中返回自定义 HTML div 吗?

Javascript - 计算对象数组中的重复项并将计数存储为新对象

android - 如何继续调试 react native 应用程序?

javascript - 第一次按下按钮时状态不会更新,但会调用函数

javascript - 存储在 FileList 中的图像未在 React 中显示

reactjs - 使用 Netlify CMS 的 Gatsby 镜像 - 字段 "image"不得有选择,因为类型 "String"没有子字段

css - Angular 6 - LESS动画在部署后不起作用

typescript - 定义类型以从类型的选定键中创建对象似乎已被破坏

javascript - 使用 Javascript/Typescript 防止 html 注入(inject)

ios - pod 可以访问主项目中的框架吗?