js。我试图执行下面的应用程序,我收到一个错误,“Uncaught TypeError: Cannot read property 'checked' of null
”任何人都可以请帮助我,为什么我得到一个空状态。为什么我无法阅读检查。为什么我的状态为空?
在接收错误Checkbox.js if语句即
if (this.state.checked) {
的index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id="react-container"></div>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Checkbox from './Checkbox';
ReactDOM.render(<Checkbox />, document.getElementById('react-container'));
Checkbox.js
import React, { Component } from 'react';
class Checkbox extends Component {
getInitialState(){
return {checked: false}
}
handleCheck(){
this.setState({checked: !this.state.checked})
}
render() {
var message
if (this.state.checked) {
message = "Checked"
} else {
message = "Unchecked"
}
return (
<div>
<label><input type = "checkbox" onChange = {this.handleCheck}></input></label>
<p>This box is {message}</p>
</div>
);
}
}
export default Checkbox;
感谢,但现在它抛出一个错误“ Checkbox.js:8 Uncaught TypeError:无法读取未定义的属性'setState'is this.setState也被弃用,我正在使用在handleCheck函数中 –
PureComponent与Component是不同的问题。无论如何,Component没有对象对齐(它在每个setState上呈现),而PureComponent进行浅层检查以避免在具有相同的道具/状态时重新呈现。 –
@DanielAndrei,这只是最后的一个建议。 –