我试图写一个from,但是它引发了这个错误:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
这是我正在编写表单的App.js
文件:
import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import './App.css';
import useStyles from '../src/styleMaker'
import { makeStyles } from '@material-ui/core/styles';
class App extends Component {
state = {
ssn: '',
}
useStyles = makeStyles(theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 200,
},
dense: {
marginTop: 19,
},
menu: {
width: 200,
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
button: {
margin: theme.spacing(1),
},
}));
classes = useStyles();
onHandleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
return (
<React.Fragment>
<form noValidate autoComplete="off">
<TextField
id=""
label="SSN"
value={this.state.ssn}
onChange={(event) => this.onHandleChange(event)}
type="number"
name='ssn'
margin="normal"
className={this.classes.textField}
/>
<TextField
id=""
label="SSN"
value={this.state.phone}
onChange={(event) => this.onHandleChange(event)}
type="number"
name='phone'
margin="normal"
className={this.classes.textField}
/>
</form>
</React.Fragment>
);
}
}
export default App;
有人可以帮助我我的代码有什么问题吗?为什么我的代码无法正常工作?
当我添加userStyle时,我会抛出错误,在这种情况下有人可以帮助我吗?
我花了几个小时来解决此问题,但现在我只是放弃了。任何人的帮助都会使我开心。.预先感谢
答案 0 :(得分:0)
不能在基于类的组件中使用挂钩。如果要使用钩子,则需要将组件转换为功能性,如下所示:
function App() {
const classes = useStyles();
...
return (
...
)
}
答案 1 :(得分:0)
由于错误提示您
只能在函数组件的主体内部调用钩子
您在这里使用的是基于类的组件,您可以将此基于类的组件转换为功能组件,还需要在功能组件中使用useState Hook作为状态,您可以这样做
const App = () => {
const [ssn, setSsn ] = useState('')
const classes = useStyles()
// remaining code
return (
....
)
}
此外,当您使用功能组件时,不能在功能组件内部使用此功能
希望有帮助