使用引用对子组件进行反应

时间:2020-08-03 19:33:49

标签: javascript reactjs react-ref

我想从父组件内部的子组件中调用函数。我知道我可以使用React createRef作为解决方案。到目前为止,我已经尝试过,但是current的值仍然为null。也许我忘记了一些东西,但我无法弄清楚。如果我可以通过其他方式修复它,那也可以。

我的例子:

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

1 个答案:

答案 0 :(得分:1)

您可以将所需的方法传递给子组件,然后从那里调用它,而不是传递ref,例如:

timestamptz

与功能组件相同

class Parent extends Component {
  example() {
    console.log("test");
  }

  render() {
    return <Child func={this.example.bind(this)} />
  }
}
class Child extends Component {
  render() {
    return <button onClick={this.props.func}>Click me</button>
  }
}