如何访问useRef值挂钩?

时间:2020-04-15 11:55:32

标签: reactjs react-native react-hooks

我正在尝试实现本机图像裁剪视图,并且正在使用: https://github.com/hhunaid/react-native-image-crop-tools#readme

经过一些修复后,显然可以自动生成一个输出:

https://ibb.co/SBLvFGY

我的问题是,我该如何获取useRef Hook的值,因为我想将其存储在redux中,所以这对我来说非常混乱,代码:

import React, { useState, useRef } from 'react';
import { Button, StatusBar, StyleSheet, View, Image } from 'react-native';
import { CropView } from 'react-native-image-crop-tools';
import ImagePicker from 'react-native-image-picker';

import { connect } from 'react-redux';
import { changeNewIdeaImage } from '../../redux/actions/';

const TestImageCropper = () => {
    const [uri, setUri] = useState();
    const cropViewRef = useRef();
    return (
        <>
            <StatusBar barStyle="dark-content" />
            <View style={styles.container}>
                <Button
                    title={'Pick Image'}
                    onPress={() => {
                        ImagePicker.launchImageLibrary(
                            { noData: true },
                            (response) => {
                                setUri(response.uri);
                            }
                        );
                    }}
                />
                {uri !== undefined && (
                    <CropView
                        sourceUrl={uri}
                        style={styles.cropView}
                        ref={cropViewRef}
                        onImageCrop={(res) => console.warn(res)}
                        keepAspectRatio
                        aspectRatio={{ width: 4, height: 4 }}
                    />
                )}
                <Button
                    title={'Get Cropped View'}
                    onPress={() => {
                        cropViewRef.current.saveImage(true, 90);

                    }}
                />
            </View>
        </>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    cropView: {
        flex: 1,
        backgroundColor: 'red',
    },
});

const mapStatetoProps = (state: any) => {};

export default TestImageCropper;

现在这对我来说是最令人困惑的部分。saveImage视图功能从何而来,如何将其连接起来,以便将Image uri保存在Redux中进行显示?

 <Button
    title={'Get Cropped View'}
                    onPress={() => {
                        cropViewRef.current.saveImage(true, 90);

                    }}
                />

谢谢!

1 个答案:

答案 0 :(得分:1)

saveImage()似乎是一种来自CropView的方法。 Ref只是在您的情况下存储呈现的CropView元素,因此cropViewRef.current本质上是CropView组件中的TestImageCropper,您可以使用以下方法调用它的内置方法cropViewRef.current.saveImage(true, 90);

我不清楚,要存储在redux中是什么? ref的值是元素本身。