动画化react native中的展开/折叠文本包装器



我是react native dev的新手,我想在按下按钮后有一个简单的扩展/滑动高度效果,我试着遵循文档,但动画是react原生的,这太荒谬了。

我的代码非常简单,我想要动画化的视图是在单击onIsExpanded回调后,用props.item.body围绕文本的视图包装器。这是观点:

const [ isExpanded, setIsExpanded ] = useState(false);
const [ maxHeight, setMaxHeight ] = useState(null);
const [ minHeight, setMinHeight ] = useState(null);
const [ animation, setAnimation ] = useState(new Animated.Value());

const toggleIsExpanded = () => 
{
setIsExpanded(!isExpanded);
};

<View style={{ width:'100%', flexDirection:'column', position:'relative',}}>
<TouchableOpacity style={{ width:'100%', height:50}} onPress={ toggleIsExpanded }>
<EntypoIcon name="chevron-small-down" style={{ color:'rgb(68,68,68)', fontSize:20 }}/>
</TouchableOpacity>
{//How to expand/collapse this?}
<View style={{ width:'100%', padding:10 }}>
<Text style={{ fontSize:14, color:'rgb(68,68,68)' }}>{ props.item.body }</Text>
</View>
</View>

有人能帮我吗?

大多数情况下,Animated在宽度、不透明度等为预先已知值的场景中工作良好。然而,在这种情况下,Text的高度完全取决于身体的长度,这是一个很难计算的值。

根据我的经验,LayoutAnimation在这些场景中效果最好,您只需在设置状态之前指示,状态更改后将发生动画。LayoutAnimation计算出其余部分。

有关详细信息,请查看文档。

更新您的代码:

const defaultAnimation = {
duration: 200,
create: {
duration: 200,
type: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity,
},
update: {
type: LayoutAnimation.Types.easeInEaseOut,
},
};

const [ isExpanded, setIsExpanded ] = useState(false);
const [ maxHeight, setMaxHeight ] = useState(null);
const [ minHeight, setMinHeight ] = useState(null);

const toggleIsExpanded = () => 
{
// This will make sure an animation is trigger after toggling
LayoutAnimation.configureNext(defaultAnimation);
setIsExpanded(prev => !prev);
};
return (
<View style={{ width:'100%', flexDirection:'column', position:'relative',}}>
<TouchableOpacity style={{ width:'100%', height:50}} onPress={ toggleIsExpanded }>
<EntypoIcon name="chevron-small-down" style={{ color:'rgb(68,68,68)', fontSize:20 }}/>
</TouchableOpacity>
{//How to expand/collapse this?}
{!!expanded && (
<View style={{ width:'100%', padding:10 }}>
<Text style={{ fontSize:14, color:'rgb(68,68,68)' }}>{ props.item.body }</Text>
</View>)}
</View>
);

最新更新