首页 > 解决方案 > 在类组件中反应 forwardRef 当前 null

问题描述

我对反应比较陌生,似乎无法弄清楚,我已经研究了一段时间,似乎没有任何效果。

我有一个使用 createRef 的父组件

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

然后将其传递给孩子&访问如下

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

但在 getState chartRef current 始终为 null

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

这是子组件

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;

任何帮助表示赞赏

标签: reactjsreact-nativereact-reduxreact-forwardref

解决方案


您可以在参考的帮助下访问父组件中的子组件,如下所示

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>
    );
  }
}

您可以在代码框示例中尝试此代码


推荐阅读