【问题标题】:Moving arrow with react native带有反应原生的移动箭头
【发布时间】:2021-08-12 20:44:16
【问题描述】:

我是本机反应的新手,我试图在变量获取值后做一个移动箭头,我考虑过使用开关盒并更改样式,但似乎不可能更改填充属性,如何我能解决这个问题吗?

【问题讨论】:

标签: javascript css react-native


【解决方案1】:

您的问题需要大量信息才能得到彻底回答,因此我假设您使用钩子,我将尝试通过给您一个示例来指导您。

整个原则是将箭头放置在“绝对”位置并使用动画对其进行动画处理。然后,您需要做的就是设置变量“arrowValue”的值,例如:setArrowValue(0.3)。然后,您的箭头将放置在距容器左侧 30% 处(根据您的插值)。

这是一个代码 sn-p 向您展示正确的方式:

import {StyleSheet, View, Animated} from "react-native";

export default function ArrowMover(props)
{
  // This is the value you will set and your arrow will automatically be placed
  const [arrowValue, setArrowValue] = React.useState(0); // From 0 to 1 for example

  // This is your animation
  // It is the value you have to change to make your arrow move
  const [animation, setAnimation] = React.useState(new Animated.Value(0));
  
  // This is an interpolation of your animation
  // See this as a black box, it allows you to output value (and ranges of values)
  // based on the value of your animation
  const animateArrowPosition = animation.interpolate({
    inputRange: [0, 1],
    outputRange: ["0%", "100%"],
  });
  
  // This is where everthing happens automatically
  React.useEffect(() =>
  {
    moveArrowTo(arrowValue);
  }, [arrowValue]); // Anytime 'arrowValue' changes, execute the 'moveArrowTo' function
  
  const moveArrowTo = (newArrowValue) =>
  {
    Animated.timing(animation, { toValue: newArrowValue, duration: 500, }).start(() =>
    {
      // Do something (or nothing) once the animation finished
    });
  };
  
  return(
    <View style={s.container}>
      // Your animation interpolation will change along with 'animation' to follow your interpolation
      // of the value
      <Animated.View style={[s.arrow, {left:animateArrowPosition}]}> // Notice the 'Animated.View'
        <View>
          // Your arrow (icon, image, etc...)
        </View>
      </Animated.View>
    </View>
  );
}

let s = StyleSheet.create(
{
  container:
  {
    // Your container style
  },
  arrow:
  {
    // Your arrow style
    height:30,
    aspectRatio:1,
    position:'absolute',
    // left:0 (no need for that, your animation is taking care of the 'left' property 
  },
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2019-05-25
    相关资源
    最近更新 更多