【发布时间】:2020-07-01 14:26:23
【问题描述】:
我不断收到错误消息
未捕获的类型错误:this.setstate 不是函数
在我的代码行中。 我正在使用 VSCode。我正在使用 Chrome 调试器,因为直接在 VSCode 中进行调试存在问题。我试图解决这个问题,但这并没有产生任何影响,最终从未得到纠正。我正在使用 VSCode 中的 LiveServer 来启动代码。有更好的配置,但我只是想运行代码。
我的代码在下面
HTML 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="Fontchoose_container"></div>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<div>
Here goes...
<!--Programmed scripts-->
<script src="./FontChooser.js" type="text/babel"></script>
....done
</div>
</body>
</html>
JS-脚本
class FontChooser extends React.Component {
constructor(props) {
super(props);
this.state = {hideElement:true}
this.text="Click on this part"
this.size=10
// this.handleClicks= this.handleClicks.bind(this)
}
handleClicks() {
if (this.state.hideElement) {
console.log(this.state)
this.setstate({hideElement:false}) //ERROR HAPPENS HERE
} else {
this.setstate({hideElement:true})
}
document.getElementById("checkbox").hidden=this.state.hideElement
document.getElementById("decreaseButton").hidden=this.state.hideElement
document.getElementById("fontSizeSpan").hidden=this.state.hideElement
document.getElementById("increaseButton").hidden=this.state.hideElement
document.getElementById("textSpan").hidden=this.state.hideElement
}
render() {
return(<div >
<button id="LaunchButton" onClick={this.handleClicks.bind(this)}>Click me</button>
<input type="checkbox" id="boldCheckbox" hidden={true}/>
<button id="decreaseButton" hidden={true}>-</button>
{ <span id="fontSizeSpan" hidden={true}>{this.props.size}</span> }
<button id="increaseButton" hidden={true}>+</button>
<span id="textSpan" hidden={true}>{this.props.text}</span>
</div>
// hidden={false}
);
}
}
ReactDOM.render( <FontChooser />, document.getElementById('Fontchoose_container'))
我查看了几个参考资料以及这篇文章,但更正没有任何区别: this.setState is undefined
我已尝试以几种不同的方式更正绑定调用,这会导致具有初始化属性的对象。在我发现的所有示例中,他们都使用了this.setstate({*/set parameters:new*/})。在我的情况下,这会导致错误,我还没有看到调用无效的原因,这是与绑定相关的问题的一部分。
【问题讨论】:
-
改用
handleClicks = () => { this.setState() }怎么样?
标签: reactjs