why material-UI textField returns 'Invalid hook call' error

给你一囗甜甜゛ 提交于 2019-12-13 03:19:43

问题


I'm trying to create a textfield from Material-UI that update state in a class component. Something is wrong and it returns 'invalid hook call' error. Must Material-UI be always used with React Hooks or could it be used without?

import React, { Component } from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      year: null,
      otherAttributes: null
    };
    this.handleChangefor = this.handleChangefor.bind(this);
  }

  handleChangefor = (propertyName) => (event) => {
    this.setState({
      ...this.state,
      [propertyName]: event.target.value
    })
  }

  render() {
    return (
      <div>
        <TextField
          id="outlined-name"
          label="year"
          value={this.state.year}
          onChange={this.handleChangefor('year')}
          margin="normal"
          variant="outlined"
          />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

The code can also be found here in online editor. Thanks.


回答1:


First, update your react version from 16.8.0 to 16.8.6.

Then, TextField value property can't be null, change your initial state to:

this.state = {
  year: "",
  otherAttributes: null
};

Except that your code works fine.



来源:https://stackoverflow.com/questions/56924813/why-material-ui-textfield-returns-invalid-hook-call-error

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