材质UI模式不起作用(React JS)

ken*_*chu 5 javascript reactjs material-ui

我正在尝试从材料ui例子中复制模式的例子,但我无法使其工作,首先我得到了“ 无法读取未定义的属性'setState'的未定义 ”,我解决了这个问题,现在在控制台,但是当我单击显示模式的按钮时,没有任何反应。

我正在使用material-ui v1.0.0-beta.31

这是代码:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Typography from 'material-ui/Typography';
import Modal from 'material-ui/Modal';
import Button from 'material-ui/Button';

function rand() {
  return Math.round(Math.random() * 20) - 10;
}

function getModalStyle() {
  const top = 50 + rand();
  const left = 50 + rand();

  return {
    top: `${top}%`,
    left: `${left}%`,
    transform: `translate(-${top}%, -${left}%)`,
  };
}

const styles = theme => ({
  paper: {
    position: 'absolute',
    width: theme.spacing.unit * 50,
    backgroundColor: theme.palette.background.paper,
    boxShadow: theme.shadows[5],
    padding: theme.spacing.unit * 4,
  },
});

class SimpleModal extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      open: false
    };
    this.handleOpen = this.handleOpen.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }

  handleOpen() {
    this.setState({ open: true });
  };

  handleClose(){
    this.setState({ open: false });
  };

  render() {
    const { classes } = this.props;

    return (
      <div>
        <Typography gutterBottom>Click to get the full Modal experience!</Typography>
        <Button onClick={this.handleOpen}>Open Modal</Button>
        <Modal
          aria-labelledby="simple-modal-title"
          aria-describedby="simple-modal-description"
          open={this.state.open}
          onClose={this.handleClose}
        >
          <div style={getModalStyle()} className={classes.paper}>
            <Typography type="title" id="modal-title">
              Text in a modal
            </Typography>
            <Typography type="subheading" id="simple-modal-description">
              Duis mollis, est non commodo luctus, nisi erat porttitor ligula.
            </Typography>
            <SimpleModalWrapped />
          </div>
        </Modal>
      </div>
    );
  }
}

SimpleModal.propTypes = {
  classes: PropTypes.object.isRequired,
};


const SimpleModalWrapped = withStyles(styles)(SimpleModal);

export default SimpleModalWrapped;
Run Code Online (Sandbox Code Playgroud)

与原始示例相比,与上面的代码的唯一区别是我添加了以下内容:

  constructor(props) {
    super(props);
    this.state = {
      open: false
    };
    this.handleOpen = this.handleOpen.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }
Run Code Online (Sandbox Code Playgroud)

谢谢!

sme*_*sme 2

this渲染按钮时尝试绑定:

<Button onClick={this.handleOpen.bind(this)}>Open Modal</Button>

同样,对于模态, onClose={this.handleClose.bind(this)}不需要这些行:

this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
Run Code Online (Sandbox Code Playgroud)