【发布时间】:2021-09-03 09:22:41
【问题描述】:
我正在构建一个 React Native Screen,其中一些内容的不透明度取决于当前的滚动状态:
state = {
scroll: new Animated.Value(0)
}
constructor(props) {
super(props)
}
componentDidMount() {
const { scroll } = this.state
scroll.addListener(({ value }) => (this._value = value))
}
renderForeground = () => {
const { scroll } = this.state
const titleOpacity = scroll.interpolate({
inputRange: [0, 106, 154],
outputRange: [1, 1, 0],
extrapolate: 'clamp'
})
return (
<View style={styles.foreground}>
<Animated.View style={{ opacity: titleOpacity }}>
<Text style={styles.message}>Do you have time to play?</Text>
</Animated.View>
</View>
)
}
render() {
const { scroll } = this.state
return (
<StickyParallaxHeader
foreground={this.renderForeground()}
scrollEvent={Animated.event([{ nativeEvent: { contentOffset: { y: scroll } } }])} />
)
}
现在我正在尝试为我的导航标题标题设置相同的不透明度(在 renderForeground() 函数中计算的 titleOpacity)。我的想法是将不透明度值转换为十六进制值并像这样设置 headerTintColor:
this.props.navigation.setOptions({headerTintColor: "#ffffff" + alpha_value})
为了使这个 alpha_value 与 titleOpacity 同步,我想在 renderForeground() 函数中使用 setState:
const { scroll } = this.state
const titleOpacity = scroll.interpolate({
inputRange: [0, 106, 154],
outputRange: [1, 1, 0],
extrapolate: 'clamp'
})
this.setState({headerOpacity: titleOpacity})
但是计划在这里已经失败,因为我收到以下错误:
已超过最大更新深度。这可能发生在组件 在 componentWillUpdate 内重复调用 setState 或 组件更新。 React 将嵌套更新的数量限制为 防止无限循环
还有其他方法可以同步滚动状态和标题标题颜色吗?
【问题讨论】:
-
设置状态会导致重新渲染,因此如果渲染组件会导致 setState,最终会导致无限循环。只是不要将状态用于不透明度;计算出来直接使用。
标签: javascript reactjs react-native react-navigation