我需要一些帮助来实现搜索和滚动以在 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
边缘情况下优雅失败的声明。
如果找到;目标 x
和 y
可以使用 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/