簡體   English   中英

在 class 組件中反應 forwardRef 電流 null

[英]React forwardRef current null in class component

我對反應比較陌生,似乎無法弄清楚,我已經研究了一段時間,似乎沒有任何效果。

我有一個使用 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 中,電流始終為 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;

任何幫助表示贊賞

您可以使用回調樣式 ref Egin 而不是將 ref 作為道具傳遞,您可以像this.handleRef一樣傳遞對 function 的引用

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

<Child ref={this.handleRef} />

您可以在參考的幫助下訪問父組件中的子組件,如下所示

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

您可以在代碼框示例中嘗試此代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM