我在循环中渲染项目,我需要得到每个项目的Y位置,以便我可以scrollTo()在事件后使用滚动到该位置.
问题是它似乎onLayout没有被正确调用,所以我得到了错误的项目位置.
示例项目:
A,B,C,D
Run Code Online (Sandbox Code Playgroud)
但我有时会为A存储位置,有时会为C等存储位置.
如何同步?
this.props.list.map((item, index) => {
return (
<TouchableOpacity
onLayout={(event) => {
let {x, y, width, height} = event.nativeEvent.layout;
....
Run Code Online (Sandbox Code Playgroud)
更新
这里是完整的代码.所以你看我设置了我找到的第一个国家索引onLayout.因此,当我按B时,它应该滚动到巴哈马的位置,但有时它会滚动到巴哈马,有时滚动到巴巴多斯,有时滚动到不丹 ......
const countries = ["Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan"];
export default class App extends Component {
constructor(props, context) {
super(props, context);
this.state = {
currentLetter: "A",
};
this.sections = {}
}
onLetter(letter) {
this.setState({currentLetter: letter});
if (this.sections[letter]) {
this.scrollView.scrollTo({ y: this.sections[letter] });
}
}
<ScrollView ref={ref => this.scrollView = ref}>
{
countries.map((item) => {
return (
<View onLayout={(event) => {
var {x, y, width, height} = event.nativeEvent.layout;
if (!this.sections[item[0]]) {
this.sections[item[0]] = y;
}
}}
style={{backgroundColor: "#f0aabb", padding: 10, margin: 5}}>
<Text>{item}</Text>
</View>
)
})
}
</ScrollView>
Run Code Online (Sandbox Code Playgroud)
我认为这onLayout不按顺序进行。所以不确定巴哈马是否会先行。
我认为你应该创建一个函数来映射字母和起始/指向项,例如:'A' = '阿富汗','B' = '巴哈马'
你可以硬编码它(不推荐,只是解释一下想法)
dataSource = { 'Afghanistan': 'A', 'Bahamas': 'B'}
// implement this func base on your rules for title and letter
getLetterFromTitle(title) {
return dataSource[title];
}
Run Code Online (Sandbox Code Playgroud)
然后onLayout
const letter = getLetterFromTitle(item);
if (letter && !this.sections[letter]) {
this.sections[letter] = y;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
122 次 |
| 最近记录: |