React ref返回null,信息为“下面的值刚刚被评估”

时间:2019-07-08 14:59:33

标签: javascript reactjs

我正在尝试获取Carousel的引用,但在this.carousel的componentDidMount值中,始终返回null,并带有“刚刚评估了下面的值”的信息。因此,我不知道何时可以计算出该值,以及如何获得不为空的电流值。

我已经阅读了有关此问题的答案,但是不幸的是,他们没有帮助我理解我做错了什么(或者例子对我没有用)

React antd carousel methods

Value arriving late? “Value below was evaluated just now”

export default class ImagePreviewCarousel extends React.Component<any, any> {

    carousel = React.createRef();

    componentDidMount() {
        console.log(this.carousel);
        console.log(this.carousel.current);
    }

    render() {
        const { url, imgList } = this.props;
        const orderLayout = document.getElementById('order-layout');
        const applicationLayout = document.getElementById('application');

        return (
            createPortal(<ImageViewer url={url} onRef={this.carousel} onClose={this.props.onClose} imgList={imgList} />, orderLayout || applicationLayout)
        )
    }
}

const ImageViewer = (props: any) => {
    console.log(props.onRef);
    return (
        <Modal 
            footer={null} 
            visible={props.onClose} 
            onCancel={props.onClose}
            bodyStyle={{ backgroundColor: '#000' }}
            width={'800px'}
        >
            <div style={{
                display: 'flex', 
                flexDirection: 'column', 
                justifyContent: 'center', 
                marginTop: 'auto', 
                marginBottom: 'auto', 
                width: '100%',
                height: '100%', 
                zIndex: 10
            }}>
                <Carousel ref={props.onRef}>
                    {props.imgList}
                </Carousel>
            </div>
        </Modal>
    );
}

P.S react版本为16.4.1

1 个答案:

答案 0 :(得分:0)

ImageViewer可以用forwardRef包装,请检查详细信息。

https://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components

希望它对您有帮助:)