reactjs - 在类组件中反应 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;
任何帮助表示赞赏
解决方案
您可以在参考的帮助下访问父组件中的子组件,如下所示
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>
);
}
}
您可以在代码框示例中尝试此代码
推荐阅读
- r - 为桑基图构建交易数据
- codeigniter - 表格中的多行打印
- r - ggplot geom_point 绘制两个分类变量并填写缺失
- html - How to ensure Script sends an email containing an HTML table with full range of data?
- docker - docker - RHEL 上的 docker-credential-secretservice
- mysql - 如何在联结表上插入值
- python - 您可以免费使用 Google Geocoding API 多少次?
- opengl - 如何在感知投影中渲染大小恒定的圆?
- sql - 如何在 SQL DW 中使用汇总分组函数错误?
- ipad - 使用移动设备时如何在 colab 上使用方向箭头键?