0

我在基于类的组件中获得输出,但我想知道如何在功能组件中完成同样的事情

class Apps extends React.Component {
  handleViewRef = ref => this.view = ref;

  bounce = () => this.view.bounce(800)

  render() {
    return (
      <View style={{margin:60}}>
      <TouchableWithoutFeedback onPress={this.bounce}>
        <Animatable.View ref={this.handleViewRef}>
          <Text>Bounce me!</Text>
        </Animatable.View>
      </TouchableWithoutFeedback>
      </View>
    );
  }
}
4

1 回答 1

0

您需要使用钩子来实现这一点:

const App = ()=>{
  const const viewRef = useRef(null);
  const bounce = useCallback(() => {
    if (viewRef.current) {
      viewRef.current.bounce(800)
    }, [viewRef]
  );
    return (
      <View style={styles.container}>
      <TouchableWithoutFeedback onPress={bounce} style={styles.container}>
         <Button ref={viewRef} rounded warning>
            <Text>Warning</Text>
          </Button>
      </TouchableWithoutFeedback>
      <Apps/>
      </View>
    );
}

useCallback不是绝对必要的,但会阻止在每次渲染时重新创建bounce回调。请参阅https://reactjs.org/docs/hooks-reference.html#userefhttps://reactjs.org/docs/hooks-reference.html#usecallback

于 2019-09-12T06:54:19.760 回答