繁体   English   中英

对子组件使用 refs 做出反应

[英]React using refs for child components

我想从父组件内部的子组件调用 function。 我知道我可以使用 React createRef 作为解决方案。 到目前为止,我试过了,但当前的值仍然是 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);

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

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

同样使用 function 组件

const Parent = () => {
  const example = () => console.log("test");

  return <Child func={example} />
}
const Child = ({func}) => {
  return <button onClick={func}>Click me</button>
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM