为什么createRef()返回current:null?

时间:2019-01-18 21:34:53

标签: reactjs

我正在尝试使用createRef来访问多个图像的clientHeight属性。但是,每次我在console.log中输入“ this.imageRef”时,返回的是{current:null}。我的反应是16.7。我没看到什么?

此外,PictureForGrid是我用来渲染并最终将clientHeight添加到state的组件。它由父级调用。我将同时包括两者,但我认为您只需要使用PictureForGrid。

有问题的组件     从'react'导入React;

class PictureForGrid extends React.Component {
constructor(props) {
    super(props);

    this.imageRef = React.createRef();
}


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


render() {

    return (
        <div>
            <img href={this.imageRef} src={this.props.source} alt= 
{this.props.description} />
        </div>
    )
}
}

export default PictureForGrid;

父组件

import React from 'react';

import PictureForGrid from '../PictureForGrid';
import '../../styles/Parent.css'
import one from '../../pics/one.jpg'
import two from '../../pics/two.jpg'
.
.
. 
.
import fourteen from '../../pics/Alyssa and Ryne/fourteen.jpg'

class Parent extends React.Component {
render() {
    return (
        <div className="picture-grid">
            <PictureForGrid source={one} description="erin working"/>
            <PictureForGrid   source={two} description="hands holding lamp" 
/>
            <PictureForGrid   source={three} description="chapel" />
            <PictureForGrid   source={four} description="dancing couple"/>
            <PictureForGrid   source={five} description="couple holding 
wedding sign"/>
            <PictureForGrid  source={six} description="couple at steeple"/>
            <PictureForGrid  source={seven} description="post wedding"/>
            <PictureForGrid  source={eight} description="groomsmen"/>
            <PictureForGrid  source={nine} description="bridal party"/>
            <PictureForGrid  source={ten} description="shower"/>
            <PictureForGrid  source={eleven} description="flowers"/>
            <PictureForGrid  source={twelve} description="water fountain"/>
            <PictureForGrid  source={thirteen} description="rings"/>
            <PictureForGrid  source={fourteen} description="ceremony"/>
        </div>
    )
}
}

export default Parent;

谢谢您的建议,因为我显然是新来的。

1 个答案:

答案 0 :(得分:1)

您有错字

更改

<img href={this.imageRef} src={this.props.source} alt= 
{this.props.description} />

收件人

<img ref={this.imageRef} src={this.props.source} alt= 
{this.props.description} />