[英]how do i update my state using a function onclick?
I'm making a simple rock paper scissors app I have an array of 'rock', 'paper', and 'scissors, and I'm mapping it.我正在制作一个简单的石头剪刀布应用程序,我有一组“石头”、“纸”和“剪刀”,我正在绘制它。 but the problem is that when i click the button it should update the state through the handle click function and should display user choice
但问题是,当我单击按钮时,它应该通过句柄单击功能更新状态并显示用户选择
here is my app component:这是我的应用程序组件:
import { useState } from "react";
const App = () => {
const [userChoice, setuserChoice] = useState(null);
const choices = ["rock", "paper", "scissors"];
const handleClick = (value) => {
console.log('hi');
setuserChoice(value);
};
return (
<div>
<h1>Userchoice is:</h1>
<h1>compute choice is :</h1>
<>
{choices.map(choice => <button key={choice} onClick={()=>handleClick(choice)}>{choice}</button>)}
</>
</div>
);
};
export default App;
here is my index.js:这是我的 index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
I was having trouble rendering the list using the map what worked for that was wrapping my map function in a fragment im new to reacting so I'm not sure.我在使用地图渲染列表时遇到了麻烦,为此我将地图函数包装在一个片段中,我不知道如何做出反应,所以我不确定。 what i want is when someone clicks on the rock button it should update the state and display rock as the user choice.
我想要的是当有人点击摇滚按钮时,它应该更新状态并显示摇滚作为用户选择。
Everything is just right, you just forgot to render userChoice state.一切都刚刚好,你只是忘了渲染 userChoice 状态。
import { useState } from 'react';
const App = () => {
const [userChoice, setuserChoice] = useState(null);
const choices = ['rock', 'paper', 'scissors'];
const handleClick = (value) => {
console.log('hi');
setuserChoice(value);
};
return (
<div>
<h1>Userchoice is: {userChoice}</h1>
<h1>compute choice is :</h1>
<>
{choices.map((choice) => (
<button key={choice} onClick={() => handleClick(choice)}>
{choice}
</button>
))}
</>
</div>
);
};
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.