我正在尝试更改 let 的值showtext
以更改显示的文本。
当我更改showtext
代码中的值时,文本会更改,但是当我单击按钮时变量不会更改。
// eslint-disable-next-line eslint-comments/disable-enable-pair
/* eslint-disable no-eval */
import * as React from "react";
import "../../../styles/colour_sdgs.css";
import "../../../styles/infotext.css";
import Logo from "../../../SDGLogos/Goal-06.png";
let showtext = 1;
const sdg = "sdg06";
const text = {
1: `text1`,
2: `text2`,
};
function incrementCount(): void {
showtext++;
}
function decrementCount(): void {
showtext--;
}
export const sdg06infotext = (): JSX.Element => {
return (
<div>
<div className={`colour_${sdg}`}>
<div className="header">
Hochwertige Bildung <img className="sdglogo" alt="logo" src={Logo} />
</div>
</div>
<div className="infotextbox">
<p> {text[showtext]} </p>
<p>blabla</p>
<p>
other text
</p>
</div>
<button type="button" onClick={incrementCount}>
{showtext}+
</button>
<button type="button" onClick={decrementCount}>
{showtext}-
</button>
</div>
);
};
showtext
单击按钮时会发生变化;没有改变的是 React 元素树,因此 DOM 保持不变——换句话说,你的应用程序的状态与视图不同步。您需要告诉 React 在showtext
更改时重新渲染。
要使其工作,您需要移动showtext
和在组件内部使用它的函数并使其成为状态值:
const sdg = "sdg06";
const text = {
1: `text1`,
2: `text2`,
};
const Sdg06infotext = () => {
let [showtext, setText] = React.useState(1);
function incrementCount(): void {
setText(++showtext);
}
function decrementCount(): void {
setText(--showtext);
}
return (
<div>
<div className={`colour_${sdg}`}>
<div className="header">
Hochwertige Bildung
</div>
</div>
<div className="infotextbox">
<p> {text[showtext]} </p>
<p>blabla</p>
<p>
other text
</p>
</div>
<button type="button" onClick={incrementCount}>
{showtext}+
</button>
<button type="button" onClick={decrementCount}>
{showtext}-
</button>
</div>
);
};
ReactDOM.render(<Sdg06infotext/>, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句