如何使用带有useRef钩子的无状态功能组件来实现以下代码

时间:2019-07-03 17:20:15

标签: reactjs react-native react-hooks ref

我在基于类的组件中有一些代码,这些代码只是呈现一些图片,当您单击它们时,图片将全屏显示,并且其位置详细信息已存储以供将来使用, 它有一些由React.createRef()管理的引用 它首先在父级“ StoryList”上创建了引用,然后在子级“ StoryThumbnail”上分配了引用,我们在其父级组件上访问了一些图像的宽度和高度 但是,如果我想使用功能组件怎么办? 我不能在那里使用create ref,是否仍然可以使用hooks和useRef来实现以下代码?

class StoryList extends React.Component{

    state = {
        story: null,
        position:null,
        active:false
    };


    thumbnails = {};


    constructor(props) {
        super(props);

        props.stories.forEach((story) => {
            this.thumbnails[story.id] = React.createRef();
        });
    }


    onRequestClose = () => this.setState({ story: null, position: null,active:false });

    goToStory = async (story) => {
        const position = await this.thumbnails[story.id].current.measure();
        console.log(position)
        this.setState({ story, position,active:true });
    }

    // {stories}  = this.props;
    render() {

        console.log(this.thumbnails)
        const { onRequestClose } = this;
        const { stories } = this.props;
        const { story, position,active } = this.state;
        return (
            <View style={styles.flex}>
                <ScrollView style={styles.flex} contentInsetAdjustmentBehavior="automatic">
                    <SafeAreaView style={styles.container}>
                        {
                            stories.map(
                                s => (
                                    <StoryThumbnail
                                        ref={this.thumbnails[s.id]}
                                        key={s.id}
                                        selected={!!story && story.id === s.id}
                                        onPress={() => this.goToStory(s)}
                                        story={s}
                                    />
                                ),
                            )
                        }
                    </SafeAreaView>
                </ScrollView>
                {
                    active && (
                        <View style={StyleSheet.absoluteFill}>
                            <StoryModal {...{ story, position, onRequestClose }} />
                        </View>
                    )
                }
            </View>
        );
    }



}


class StoryThumbnail extends React.Component{



    ref = React.createRef();


    render() {
        const { ref } = this;
        const { story, onPress, selected } = this.props;
        return (
            <TouchableWithoutFeedback {...{ onPress }}>
                <View style={styles.container}>
                    {
                        !selected && (
                            <Image source={story.source} style={styles.image} ref={ref} />
                        )
                    }
                </View>
            </TouchableWithoutFeedback>
        );
    }

}

0 个答案:

没有答案