如何在React中更改鼠标事件上的文本



我试图在react中使用onMouseDown事件来更改文本,但它不起作用。我看到了一个类似的代码,它确实有效,所以我不知道可能出了什么问题。

import React, { Component } from "react";
import "./ContentComponent.css";
class Content extends Component{
constructor(){
super()
this.onClickForward = this.onClickForward.bind(this)
this.onClickBack = this.onClickBack.bind(this)
const img0 = require('./images/dog1.jpg');
const img1 = require('./images/dog2.jpg');
const img2 = require('./images/dog3.jpg');
const img3 = require('./images/dog4.jpg');
this.state={
index: 0,
imgList: [img0, img1, img2, img3]
}
this.state2 = {
tekst: "Pies"
}

}
onClickForward(){
if (this.state.index + 1 === this.state.imgList.lenght) {
this.setState({
index: 0
})
} else{
this.setState({
index: this.state.index +1
})
}
}
onClickBack(){
if (this.state.index - 1 === -1) {
this.setState({
index: this.state.imgList.lenght -1
})
} else{
this.setState({
index: this.state.index - 1
})
}
}
zmianaTekstu() {
this.setState2({
tekst: "Pies domowy - udomowiony gatunek ssaka drapieżnego z rodziny psowatych, traktowany przez niektóre ujęcia systematyczne za podgatunek wilka."
})
}
render(){
return(
<div className="info">
<img src={this.state.imgList[this.state.index]} alt="" className="mainImage" />
<div className="btns">
<button onClick={this.onClickBack}>Poprzednie</button>
<button onClick={this.onClickForward}>Następne</button>
</div>
<div className="textInfo">
<h3 onMouseDown={() => this.zmianaTekstu()}>Click to change text</h3>
<p>{this.state2.tekst}</p>
</div>
</div>
)
}
}
export default Content;

Console说

未捕获类型错误:this.setState2不是函数

点击按钮时更改图像的第一个状态实际上有效,但我已经粘贴了整个代码,因为可能有一些交互。

在class Component中,您应该只使用一个react的状态,这样就可以访问setState并更新它。状态是一个对象,因此它可以在其中包含更多的变量、数组,甚至更多的对象。只需保持在同一状态,可用于tekst

并像更新第一个状态一样更新它,就像这样:

this.state = {
index: 0,
imgList: [img0, img1, img2, img3],
tekst: 'pies',
}

然后随时更新状态,就像这样:

this.setState({
tekst: "Pies domowy - udomowiony gatunek ssaka drapieżnego z rodziny psowatych, traktowany przez niektóre ujęcia systematyczne za podgatunek wilka."
})

setState方法是特定于您的组件的,您不能使用另一种方法来修改组件中的另一种状态,您可以将所有数据放在第一个状态对象中,也可以使用状态挂钩?

最新更新