【发布时间】:2020-08-03 19:33:49
【问题描述】:
我想从父组件内部的子组件调用一个函数。我知道我可以使用 React createRef 作为解决方案。到目前为止,我尝试过,但 current 的值仍然为空。也许我忘记了什么,但我无法弄清楚。如果我可以通过其他方式修复它也很好。
我的例子:
import * as React from 'react';
import FormComponent from "./FormComponent";
import CalendarComponent from "./CalendarComponent";
import LinearProgress from '@material-ui/core/LinearProgress';
import {connect} from "react-redux";
import DialogComponent from "../../../shared/modules/dialog/components/DialogComponent";
class WeeklyTimeTrackingComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
dialogOpen: false
}
this.formComponentRef = React.createRef();
this.openDialog = this.openDialog.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleSave = this.handleSave.bind(this);
}
openDialog = () => {
this.setState({dialogOpen: true});
}
handleClose() {
this.setState({
dialogOpen: false
});
}
handleSave() {
console.log(this.formComponentRef.current, "COMPONENTS REFS");
}
render(){
return (
<div className="weekly-timetracking">
{this.props.isFetching && (
<LinearProgress />
)}
<CalendarComponent />
<DialogComponent
open={this.state.dialogOpen}
onHandleClose={this.handleClose}
onHandleSave={this.handleSave}
title="Add new time registration"
buttonText="Save">
<FormComponent ref={this.formComponentRef} />
</DialogComponent>
<button
className="btn btn-primary"
onClick={this.openDialog}
>Add project</button>
</div>
)
}
}
const mapStateToProps = state => {
return {
isFetching: state.timeTracking.isFetching || false
};
};
export default connect(mapStateToProps)(WeeklyTimeTrackingComponent);
【问题讨论】:
标签: javascript reactjs react-ref