【问题标题】:react native: change style property on scroll scrollview反应原生:更改滚动滚动视图上的样式属性
【发布时间】:2020-12-07 13:46:53
【问题描述】:

我在滚动视图 (flex: 1) 上方有一个视图 (flex: 0)。当我在滚动视图(event.nativeEvent.contentOffset.y > 0)上向下滚动时,我想更改顶视图的边框底部颜色。

当前代码:


const Screen = (props) => {
  // ...

  const [bottom, setBottom] = useState(0);

  const scrollE = (event) => {
    setBottom(event.nativeEvent.contentOffset.y > 0 ? 1 : 0);
  };

  return (
    <View style={{ flex: 1 }}>
      <View style={{ flex: 0, borderBottomWidth: bottom, borderBottomColor: 'black' }}>
        <Text>HEADER</Text>
      </View>
      <ScrollView style={{ flex: 1 }} contentContainerStyle={{ flexGrow: 1 }} onScroll={scrollE} scrollEventThrottle={16}>
        // ... scrollview content
      </ScrollView>
    </View>
  );
};

滚动时我的屏幕似乎在闪烁。我认为每次我的边界状态发生变化时,它都与重新渲染有关。我尝试使用 use ref 将其更改为此,但这也不起作用:

const Screen = (props) => {
  // ...

  const bottom = useRef(0);

  const scrollE = (event) => {
    bottom.current = event.nativeEvent.contentOffset.y > 0 ? 1 : 0;
  };

  return (
    <View style={{ flex: 1 }}>
      <View style={{ flex: 0, borderBottomWidth: bottom.current, borderBottomColor: 'black' }}>
        <Text>HEADER</Text>
      </View>
      <ScrollView style={{ flex: 1 }} contentContainerStyle={{ flexGrow: 1 }} onScroll={scrollE} scrollEventThrottle={16}>
        // ... scrollview content
      </ScrollView>
    </View>
  );
};

我不需要调整大小的“粘性”标题,我只希望更改边框底部宽度。

【问题讨论】:

  • 你从哪里通过底部(参考)?
  • 无处可去。我需要把它传递到某个地方吗?您可以使用 useRef 而不将其分配给我认为的对象...
  • 当您描述 ref const ref = useRef(); 并将其传递给某个组件 &lt;Component ref={ref} ... /&gt; 时,然后 ref.current 为您提供对该组件的引用。
  • 是的,我知道,但在这种情况下我不需要对组件的引用……您还可以将值存储在 useRef 常量中,而不会在重新渲染时丢失值。跨度>
  • 你能给我一个小吃网址吗?我会尽力帮助你的。

标签: react-native


【解决方案1】:

我会用动画 API 来做,希望这会有所帮助

 const Screen = (props) => {
  const scrollY= new Animated.Value(0)

  const scrollE = (event) => {
   Animated.event([{ nativeEvent: { contentOffset: { y: scrollY } } }],{ useNativeDriver: true })
  };

const bottom = scrollY.interpolate({
    inputRange: [0, 10],
    outputRange: [1, 0],
})

  return (
    <View style={{ flex: 1 }}>
      <View style={{ flex: 0, borderBottomWidth: bottom, borderBottomColor: 'black' }}>
        <Text>HEADER</Text>
      </View>
      <ScrollView style={{ flex: 1 }} contentContainerStyle={{ flexGrow: 1 }} onScroll={scrollE} scrollEventThrottle={16}>
        // ... scrollview content
      </ScrollView>
    </View>
  );
};

【讨论】:

    猜你喜欢
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多