我写了第一个与打字稿互动的组件:一个简单的计数器。
树是:索引->应用程序(react / js)->计数器(react / js)。
单击按钮,即可增加/减少state.count。我看到了console.log,但是点击时未更新带有{state.count}的标记?
为什么?我的错误在哪里?
谢谢您的帮助。
我试图将key属性添加到div标签。
Counter.tsx
import React from "react";
interface IState {
count: number;
}
export default function Counter(): JSX.Element {
const state: IState = { count: 0 };
const increment = (): any => {
console.log(state);
state.count= state.count + 1
};
const decrement = (): any => {
console.log(state);
state.count = state.count - 1;
};
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={decrement}>-</button>
<div key={state.count}>{state.count}</div>
<button onClick={increment}>+</button>
</div>
</div>
);
}
App.tsx
import React from 'react'
import Counter from "./counter";
export default function App():JSX.Element {
return (
<div>
<Counter />
</div>
);
}
index.tsx
import React from 'react'
import ReactDOM from "react-dom";
import App from './components/App'
const root = document.getElementById('app-root')
ReactDOM.render(<App />, root);
我希望通过单击按钮来更改数字。
答案 0 :(得分:4)
您正在改变状态!!试试这个:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Random Color Slot Game</title>
<link rel="stylesheet" type="text/css" href="slots.css"/>
<script src="colorSlots.js"> </script>
</head>
<body>
<h1>Welcome to my random color slot game!</h1>
<button onclick = "document.getElementsByClassNames('pick').innerHtml='inputNum()'">click to play</button>
<div>
<div class="pick" id="one"></div>
<div class="pick"></div>
<div class="pick"></div>
<div class="pick"></div>
<div class="pick"></div>
</div>
</body>
</html>
const element= document.getElementsByClassName('pick');
let color = ['red','orange','yellow','green','blue','purple']
function inputNum(){
for(i=0; i<element.length; i++){
element[i]
}
const rand = Math.floor(Math.random()*color.length){
return 'document.getElementsByClassName("pick").style.'+ rand
}
答案 1 :(得分:0)
以下代码可解决问题:
import React,{useState} from "react";
interface IState {
count: number;
}
export default function Counter(): JSX.Element {
const [count, setCounter] = useState(0);
const state: IState = { count: 0 };
const increment = (): any => {
console.log(state);
setCounter(count+1);
};
const decrement = (): any => {
console.log(state);
setCounter(count -1);
};
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={decrement}>-</button>
<div key={count}>{count}</div>
<button onClick={increment}>+</button>
</div>
</div>
);
}