为什么 material-UI textField returns 'Invalid hook call' 错误
why material-UI textField returns 'Invalid hook call' error
我正在尝试从 Material-UI 创建一个文本字段,在 class 组件中更新状态。出了点问题,它 returns 'invalid hook call' 错误。 Material-UI 必须始终与 React Hooks 一起使用还是可以不使用?
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);
代码也可以在在线编辑器中找到 here。谢谢。
首先,将您的 React 版本从 16.8.0
更新为 16.8.6
。
那么,TextField
value
属性就不能null
,把你的初始状态改成:
this.state = {
year: "",
otherAttributes: null
};
除了你的 code works fine.
我正在尝试从 Material-UI 创建一个文本字段,在 class 组件中更新状态。出了点问题,它 returns 'invalid hook call' 错误。 Material-UI 必须始终与 React Hooks 一起使用还是可以不使用?
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);
代码也可以在在线编辑器中找到 here。谢谢。
首先,将您的 React 版本从 16.8.0
更新为 16.8.6
。
那么,TextField
value
属性就不能null
,把你的初始状态改成:
this.state = {
year: "",
otherAttributes: null
};
除了你的 code works fine.