【发布时间】:2021-02-11 07:42:09
【问题描述】:
我正在尝试实现一个平面列表,可以在其中扩展项目以显示其他数据。 我的问题是 onLayout() 有时(〜一半时间)不会给我内容的完整高度(不会返回大于 0 的高度 => 无法显示附加数据)
这是我的自定义组件:
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import Animated, { Easing } from 'react-native-reanimated';
const { Value, timing } = Animated;
export default class ResultElement extends React.Component {
constructor(props) {
this.state = {
expanded: false,
contentHeight: 0,
};
this._initContentHeight = this._initContentHeight.bind(this);
}
height = new Value(0);
toggle() {
timing(this.height, {
toValue: this.state.expanded ? 0 : this.state.contentHeight,
duration: 300,
easing: Easing.inOut(Easing.ease),
}).start();
this.setState({ expanded: !this.state.expanded });
}
_initContentHeight(evt) {
if (this.state.contentHeight > 0) return;
const height = evt.nativeEvent.layout.height;
this.setState({ contentHeight: height });
this.height.setValue(this.state.expanded ? this.state.contentHeight : 0);
}
render() {
const item = this.props.item;
return (
<View key={item.id}>
<View style={{ flex: 1 }}>
<TouchableOpacity onPress={() => { this.toggle(); }}>
<Text>Toggle content below</Text>
</TouchableOpacity>
<Animated.View style={[{ overflow: 'hidden' }, { height: this.height }]} onLayout={(evt) => this._initContentHeight(evt)}>
<Text>Random Height content here</Text>
</Animated.View>
</View>
</View>
);
}
}
这是平面列表:
<FlatList
data={plan.timeline}
renderItem={({ item }) => <ResultElement item={item} />}
ref={(ref) => { this.flatListRef = ref; }}
/>
谁能解释为什么这个问题不会一直出现?
【问题讨论】:
-
我用array.map替换了flatlist,但问题仍然存在,所以问题是自定义组件。仍在寻找如何解决它...
标签: javascript react-native react-native-flatlist react-native-reanimated