收听PanResponder以更改状态值

时间:2017-03-29 13:53:34

标签: javascript react-native jsx

我对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()函数。 在渲染过程中更改状态是一个非常糟糕的主意。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

Soooo,我找到了解决方案

基本上在React中,视图正在监听组件的状态:所以要#34;重新渲染&#34;我们需要改变状态。

因此,我在泛响应者中添加了一个简单的更改:

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>
}
相关问题