【问题标题】:How to have obSubmit and onChange events for file upload in form in react, material-ui?如何在 react、material-ui 中以表单形式上传文件的 onSubmit 和 onChange 事件?
【发布时间】:2019-01-06 15:45:04
【问题描述】:

我正在构建一个简单的 React 组件。它有Upload 上传文件的按钮。我无法让onSumbit 在我当前的代码中触发:

import React from 'react';
import PropTypes from 'prop-types';
import Typography from '@material-ui/core/es/Typography/Typography';
import Button from '@material-ui/core/es/Button/Button';
import { UploadCSVstyles } from '../styles/Material-UI/muiStyles.js';
import withStyles from '@material-ui/core/es/styles/withStyles';

import * as log from 'loglevel';
log.setLevel("debug");

class UploadCSV extends React.Component {
  state = {
    uploadedFile: null
  }

  onSubmit = e => {
    e.preventDefault();
    log.debug('from submit');
    this.setState({
      uploadedFile: e.target.files[0]
    });
  }

  onChange = e => {
    log.debug('from change');
    this.setState({
      uploadedFile: e.target.files[0]
    });
  }

render() {
    const { classes } = this.props;
    return (
      <div>
        <Typography>
          You can upload a CSV file containing app id's in one columns.
        </Typography>
        <input
          accept="text/csv"
          className={classes.input}
          id="contained-button-file"
          multiple
          type="file"
          onChange={this.onChange}
        />
        <label htmlFor="contained-button-file">
          <Button variant="contained" component="span" className={classes.button}>
            Choose files
          </Button>
        </label>
        <form onSubmit={this.onSubmit}>
          <Button variant="contained" component="span" className={classes.button}
                  type="submit">
            Upload
          </Button>
        </form>
      </div>
    );
  }
}

UploadCSV.propTypes = {
  classes: PropTypes.object.isRequired
};

export default UploadCSV;

我认为问题在于 Material-UI 按钮,因为它不会触发 onSubmit。 如何使 onSubmit 事件与 Material-UI Button 一起使用?

【问题讨论】:

  • 您想在文件更改后触发submit 事件而不等待Upload 按钮单击吗?还是仅在您单击Upload 按钮时触发它?
  • 你遇到了什么错误?
  • 这里似乎工作正常:stackblitz.com/edit/react-1bqxqj
  • @Colin 我在您的代码中没有看到Choose files 按钮的代码
  • 我刚刚复制并粘贴了您的代码。酷,很高兴它有效!

标签: reactjs forms material-ui


【解决方案1】:

与您上面的代码相比,在功能组件中它很容易实现。唯一的技巧是将您的 onSubmit() 方法作为道具传递给您的组件。这是怎么做的;

// From where component is called 

const componentCalled = () => {

    const handleSubmit = () => {
        // do something here
    }

    return (
        <myComponent handleSubmit={handleSubmit} />
    )
}

你的组件可能看起来像;


const MyComponent = ({handleSubmit}) => {
    return (
        <Button variant="contained" component="span" className={classes.button}
                 onClick={handleSubmit}>
            Upload
          </Button>
    )
}

【讨论】:

    猜你喜欢
    • 2020-03-25
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多