首页 > 解决方案 > this.refs x useRef(有什么相似之处吗?)

问题描述

我正在尝试使用一个使用 this.ref 的库,但我必须将它传递给钩子。我不明白。

原始代码:

      import ViewShot from "react-native-view-shot";

      class ExampleCaptureOnMountManually extends Component {
        componentDidMount () {
          this.refs.viewShot.capture().then(uri => {
            console.log("do something with ", uri);
          });
        }
        render() {
          return (
            <ViewShot ref="viewShot" options={{ format: "jpg", quality: 0.9 }}>
              <Text>...Something to rasterize...</Text>
            </ViewShot>
          );
        }
      }

我的钩子代码:

    export default function screenshot() {
      const refs = useRef();

      refs.viewShot.capture().then(uri => {
        console.log('do something with ', uri);
      });

      return (
        <View style={styles.container}>
          <View style={styles.header} />
          <ViewShot ref="viewShot" options={{format: 'jpg', quality: 0.9}}>
            <View>
              <Text>Hello World</Text>
            </View>
          </ViewShot>

          <View style={styles.footer}>
            <Button title="print" onPress={onCapture} />
          </View>
        </View>
      );
    }

链接库: https ://github.com/gre/react-native-view-shot

标签: reactjsreact-native

解决方案


使用useRef(),你不这样做const refs = useRef();,你声明 ref:

const viewShot = useRef();

然后在ref属性中传递它:

<ViewShot ref={viewShot} ...

您现在应该将其用作viewShot.current.

尽管如此,由于您的原始代码在 中执行componentDidMount,现在您还应该使用useEffect(注意添加.current):

useEffect(() => {
  viewShot.current.capture().then(uri => {
    console.log('do something with ', uri);
  });
}, [])

所以:

export default function screenshot() {
  const viewShot = useRef();

  useEffect(() => {
    viewShot.current.capture().then(uri => {
      console.log('do something with ', uri);
    });
  }, [])

  return (
    <View style={styles.container}>
      <View style={styles.header} />
      <ViewShot ref={viewShot} options={{format: 'jpg', quality: 0.9}}>
        <View>
          <Text>Hello World</Text>
        </View>
      </ViewShot>

      <View style={styles.footer}>
        <Button title="print" onPress={onCapture} />
      </View>
    </View>
  );
}

推荐阅读