[英]How to change text on mouse event in 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;
setState 方法特定于您的组件,您不能使用其他方法来修改组件中的其他状态,您可以将所有数据放在第一个状态对象中或也使用状态挂钩?
"您应该在类组件中只使用一个反应的状态,这样可以访问 setState 并更新它。 状态是一个对象,因此它可以在其中包含更多变量、数组甚至更多对象。 只是保持在相同的状态,tekst 的变量
并像更新第一个状态一样更新它,如下所示:
this.state = {
index: 0,
imgList: [img0, img1, img2, img3],
tekst: 'pies',
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.