简体   繁体   中英

React forwardRef current null in class component

I'm relatively new to react & can't seem to figure it out, I have researched this for sometime now & nothing seems to work.

I have a parent component where I'm using createRef

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.chartRef = React.createRef();
    }

Then pass it to child & access is like following

<Grid item xs={12}>
   <Child
      ref={this.chartRef}
    />
    <Button onClick={this.getState}> get ref info</Button>
</Grid>

But in getState chartRef current is always null

getState = () => {
        console.log(this.chartRef.current);
    };

Here is the child component

class Child extends React.Component {
    componentDidMount() {
        this.props.registerPlugins.forEach(plugin => {
            Chart.pluginService.register(plugin);
        });
    }

    render = () => {
        const { data, options, plugins, height } = this.props;

        const updatedOptions = {
            ...options
        };

        return <div>
            <Line
                height={height}
                data={data}
                options={updatedOptions}
                plugins={plugins}/>
        </div>;
    };
}


Child.propTypes = {
    height: PropTypes.number.isRequired,
    data: PropTypes.object.isRequired,
    options: PropTypes.object.isRequired,
    plugins: PropTypes.array,
    registerPlugins: PropTypes.array,
};

export default Child;

Any help is appreciated

You could use the callback style ref Eginstead of passing your ref as the prop, you can pass in a reference to a function like this.handleRef

handleRef = r => {
    this.chartRef.current = r;
};

<Child ref={this.handleRef} />

You can access child component in parent with help of reference as like below

import React from "react";
import { Button, View } from "react-native";
import Child from "./Child";

class App extends React.Component {
  constructor() {
    super();
    this.chartRef = React.createRef();
  }
  render() {
    return (
      <View>
        <Child ref={(r) => (this.chartRef = r)} />
        <Button
          title="Parent Button"
          onPress={() => {
            console.log(this.chartRef);
          }}
        ></Button>
      </View>
    );
  }
}

export default App;

// Child.js

import React from "react";
import { Button } from "react-native";

export default class Child extends React.Component {
  constructor() {
    super();
  }
  render() {
    return (
      <Button
        title="Child Button"
        onPress={() => {
          alert("Child");
        }}
      ></Button>
    );
  }
}

you can try this code on codesandbox example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM