创建没有构造函数和绑定错误的ReactJS类

时间:2019-05-16 19:39:30

标签: reactjs

我正在使用以下代码,但是当我在框中键入文本时,它会显示错误,提示信息不多。我的目标是能够在文本框中键入和显示文本。

import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import CardMedia from '@material-ui/core/CardMedia';
import { withStyles } from '@material-ui/core/styles';
import CardActionArea from '@material-ui/core/CardActionArea';
import { Card, CardContent } from "@material-ui/core";
import IconButton from '@material-ui/core/IconButton';
import PhotoCamera from '@material-ui/icons/PhotoCamera';
import Videocam from '@material-ui/icons/Videocam';
import TextField from '@material-ui/core/TextField';

const styles = (theme) => ({
    input: {
        display: 'none'
    }
});

class MediaCapture extends Component {
    state = {
        topText: '',
        bottomText: '',
    };    

    handleChange (event) {
      const {name, value} = event.target
      this.setState({ [name]: value })
    }

    render() {
        return (
            <Fragment>                
                <Card >
                    <CardContent >
                      <TextField
                        id="standard-name"
                        label="Top Text"
                        name = "topText"
                        value={this.state.topText}
                        onChange={this.handleChange}
                        margin="normal"
                        variant="filled"
                      />                      
                    </CardContent>
                </Card>
            </Fragment>
        );
    }
}

export default withStyles(styles, { withTheme: true })(MediaCapture);

1 个答案:

答案 0 :(得分:2)

尝试将handleChange声明为箭头函数,该函数将其this自动绑定到当前上下文(与在构造函数中使用this.handleChange = this.handleChange.bind(this)相同)。

handleChange = (event) => {