Pass function as argument to material ui function

允我心安 提交于 2020-07-10 07:36:23

问题


I'm using material UI with react. I have a main component:

import React, { Component } from 'react';
import CreateNewGarden from './CreateNewGarden';

const cookies = new Cookies();

class Dashboard extends Component {
  constructor(props) {
    super(props);

    this.state = {

    };
    this.test = this.test.bind(this);
  }

  test() {
    console.log("SUCCESS")
  }

  setCookie() {
    cookies.set('access_token', this.props.access_token);
  }


  render() {
    this.setCookie();

    return (
           <CreateNewGarden myFunction={this.test}/>
        )};

  }
}

const mapStateToProps = (state) => ({

});

Dashboard.propTypes = {

};

export default withTranslation()(withRouter(connect(mapStateToProps)(Dashboard)));

Here I want to send the function test to my CreateNewGarden function

My CreateNewGarden is code from material ui (copy paste):

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Dialog from '@material-ui/core/Dialog';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import MuiDialogContent from '@material-ui/core/DialogContent';
import MuiDialogActions from '@material-ui/core/DialogActions';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import Typography from '@material-ui/core/Typography';
import Slider from '@material-ui/core/Slider';
import { useTranslation } from 'react-i18next';
import measureLogo from '../../assets/images/measure.png';
import { Button } from '../../components';
import AuthenticationService from '../../api/AuthentificationService';

const styles = (theme) => ({
  root: {
    margin: 0,
    padding: theme.spacing(2),
  },
  closeButton: {
    position: 'absolute',
    right: theme.spacing(1),
    top: theme.spacing(1),
    color: theme.palette.grey[500],
  }
});

const DialogTitle = withStyles(styles)((props) => {
  const {
    children, classes, onClose, ...other
  } = props;
  return (
    <MuiDialogTitle disableTypography className={classes.root} {...other}>
      <Typography variant="h6">{children}</Typography>
      {onClose ? (
        <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
          <CloseIcon />
        </IconButton>
      ) : null}
    </MuiDialogTitle>
  );
});

const DialogContent = withStyles((theme) => ({
  root: {
    padding: theme.spacing(2)
  }
}))(MuiDialogContent);

const DialogActions = withStyles((theme) => ({
  root: {
    margin: 0,
    padding: theme.spacing(1)
  }
}))(MuiDialogActions);


export default function CustomizedDialogs(e) {
  const [open, setOpen] = React.useState(false);
  // eslint-disable-next-line no-unused-vars
  const [height, setHeight] = React.useState(0);
  // eslint-disable-next-line no-unused-vars
  const [width, setWidth] = React.useState(0);

  const setSizeHeight = () => (e, value) => {
    setHeight(value);
  };

  const setSizeWidth = () => (e, value) => {
    setWidth(value);
  };

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const { t } = useTranslation();


  return (
    <div className="marginCardComponent">
      <Button
        onClick={handleClickOpen}
        text="dashboard.createGardenBtn"
        type="submit"
      />
      <Dialog onClose={handleClose} aria-labelledby="customized-dialog-title" open={open}>
        <DialogTitle id="customized-dialog-title" className="centerText" onClose={handleClose}>
          {t('dashboard.createGardenTitle')}
        </DialogTitle>
        <DialogContent className="logoMeasureParent">
          <img src={measureLogo} alt="Logo" className="logoMeasure centerText" />
        </DialogContent>
        <DialogContent dividers>
          <Typography className="centerText" gutterBottom>
            { t('dashboard.createGardenDetail') }
          </Typography>
        </DialogContent>
        <div className="marginLeft3">
          <p>{ t('dashboard.height') }</p>
        </div>
        <div className="centerSlider">
          <Slider
              /* eslint-disable-next-line react/destructuring-assignment */
            defaultValue={0}
            aria-labelledby="discrete-slider"
            valueLabelDisplay="auto"
            step={1}
            marks
            min={1}
            max={20}
            onChange={setSizeHeight()}
          />
        </div>
        <div className="marginLeft3">
          <p>{ t('dashboard.width') }</p>
        </div>
        <div className="centerSlider">
          <Slider
              /* eslint-disable-next-line react/destructuring-assignment */
            defaultValue={0}
            aria-labelledby="discrete-slider"
            valueLabelDisplay="auto"
            step={1}
            marks
            min={1}
            max={20}
            onChange={setSizeWidth()}
          />
        </div>
        <DialogActions>
          <Button
            onClick={handleClose}
            text="dashboard.cancelBtn"
            type="submit"
          />
          <Button
            onClick={this.props.myFunction}
            text="dashboard.createGardenBtn"
            type="submit"
          />
        </DialogActions>
      </Dialog>
    </div>
  );
}

My button try to call the onClick={this.props.myFunction} but it is not recognized.

How can I call my function ?

Thank you,


回答1:


CustomizedDialogs is a functional component and hence this.props is not defined for it. You must use props from argument. In your case you have named it e but calling it props would be more readable

export default function CustomizedDialogs(props) {
  ...
  return (
    <div className="marginCardComponent">
      ...
          <Button
            onClick={props.myFunction}
            text="dashboard.createGardenBtn"
            type="submit"
          />
      ...
    </div>
  );
}


来源:https://stackoverflow.com/questions/62040838/pass-function-as-argument-to-material-ui-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!