我对 React Native 还很陌生,我遇到了一个问题:
我了解了可以使用 PanResponder
然后使用 interpolate
函数进行的转换。
示例:
let cardOpacity = {opacity: this.state.pan.x.interpolate({inputRange: [-150, 0, 150], outputRange: [0.9, 0, 0.9]})};
我面临的问题有点棘手,因为我想从此插值中提取值而不是任何样式:
我希望该代码基本上可以工作:
_renderApplyOrDislikeHint() {
let cardOpacity = {opacity: this.state.pan.x.interpolate({inputRange: [-150, 0, 150], outputRange: [0.9, 0, 0.9]})};
let value = {opacity: this.state.pan.x.interpolate({inputRange: [-150, 0, 150], outputRange: [1, 0, 1]})};
this.state.pan.x.addListener(({value}) => {
this.x = value._value
console.log('Value changed', this.x);
});
let dimensionStyle = {
backgroundColor: 'white',
width: this.props.cardWidth,
height: this.props.cardHeight,
position: 'absolute'
};
return (
<Animated.View style={[dimensionStyle, cardOpacity]}>
{this.renderHint()}
</Animated.View>
)
}
renderHint(){
console.log('X in render hint', this.x)
return this.x > 0 ? <Text>Yes</Text> : <Text>Nope</Text>
}
问题是动画值非常适合样式,但它们不会强制重新渲染 renderHint()
函数。
在渲染过程中改变状态是一个非常糟糕的主意。
我怎样才能实现这一目标?
最佳答案
太好了,我找到了解决办法
基本上在 React 中, View 正在监听组件的状态:因此要“重新渲染”,我们需要更改状态。
因此我在平移响应器中添加了一个简单的更改:
onPanResponderGrant: (e, gestureState) => {
this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value});
this.state.pan.setValue({x: 0, y: 0});
this.state.pan.x.addListener(({value}) => {
if (value < 0 && this.state.right){
this.setState({right: false})
}
else if (value > 0 && !this.state.right){
this.setState({right: true})
}
});
}
然后只听属性:
renderHint(){
return this.state.right > 0 ? <Text>Right</Text> : <Text>Left</Text>
}
关于javascript - 监听 PanResponder 来改变状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43095551/