javascript - 在 React 中单击时单选按钮没有明显变化
问题描述
我有一个带有单选按钮的 React 站点。单击按钮时,它会记录正确的状态值,但按钮本身不会更改以指示它已被单击。
此外,当用户单击提交按钮时,即使用户选择了正确的答案,它也会在 handleSubmit 中执行 !== 操作。
GitHub:https ://github.com/irene-rojas/word-guess
我找不到阻止它工作的断开连接。
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
const words =
[
{word: "baggage", id: 1},
{word: "fan", id: 2},
{word: "charge", id: 3},
// a bunch more words all in this format
{word: "candid", id: 67}
];
class App extends Component {
state = {
word: "",
wordId: "",
targetWordArray: [],
def: "",
wordChoice1: [],
wordChoice2: [],
wordChoice3: [],
choices: [],
userChoice: [],
}
componentDidMount() {
this.resetGame();
}
generateWordArray = () => {
let newChoices = [];
let wordChoice1 = words[Math.floor(Math.random() * words.length)];
// console.log(wordChoice1);
this.setState({
wordChoice1: wordChoice1
});
newChoices.push(wordChoice1);
let wordChoice2 = words[Math.floor(Math.random() * words.length)];
// console.log(wordChoice2);
this.setState({
wordChoice2: wordChoice2
});
newChoices.push(wordChoice2);
let wordChoice3 = words[Math.floor(Math.random() * words.length)];
// console.log(wordChoice3);
this.setState({
wordChoice3: wordChoice3
});
newChoices.push(wordChoice3);
console.log(newChoices);
this.setState({
choices: newChoices
});
// prevent repeat words in array
if (wordChoice1.id === wordChoice2.id || wordChoice1.id === wordChoice3.id || wordChoice2.id === wordChoice3.id) {
this.generateWordArray();
}
return newChoices;
}
resetGame = () => {
let wordArray = this.generateWordArray();
let targetWord = wordArray[Math.floor(Math.random() * wordArray.length)];
// console.log(`targetWord = ${targetWord}`);
let targetWordArray = this.state.targetWordArray;
targetWordArray.push(targetWord);
let word = targetWord.word;
let wordId = targetWord.id;
this.setState({
word: word,
wordId: wordId,
targetWordArray: targetWordArray[0]
});
console.log(this.state.targetWordArray[0]);
console.log(`word = ${word}`);
console.log(`wordId = ${wordId}`);
// API call
axios.get(`https://www.dictionaryapi.com/api/v3/references/collegiate/json/${word}?key=${process.env.REACT_APP_MW_API_KEY}`)
.then(res => {
const result = res.data[0].def[0].sseq[0][0][1].dt[0][1]; // shortdef
const defResult = result.replace(/{bc}|{it}|a_link|d_link|sx/gi, "").replace(/[^a-zA-Z0-9(*), ]/gi, "");
//1st replace: specific exclusions. 2nd replace: protected items
this.setState({
def: defResult
});
console.log(`definition = ${defResult}`);
});
}
handleRadioClick = (event) => {
// no event.preventDefault(); because want it to work on first click
// not visibly changing radio button but it is logging the selection
let radioClick = event.target.value;
this.setState({
userChoice: radioClick
}, () => {
console.log(`ID = ${radioClick}`);
// callback to update console log in real time
})
};
handleSubmit = (event) => {
event.preventDefault();
console.log(`userChoice = ${this.state.userChoice}`);
console.log(`wordId = ${this.state.wordId}`);
if (this.state.userChoice === this.state.wordId) {
console.log("hurray!");
// this.resetGame();
};
if (this.state.userChoice !== this.state.wordId) {
console.log("nope!");
// this.resetGame();
};
// showing nope on all answers, right or wrong
}
render() {
return (
<div className="App">
<div className="header">
<h1 className="title">Title Goes Here</h1>
<div>Instructions here</div>
</div>
<div className="contentDiv">
<div className="def">
Definition: {this.state.def}
</div>
<div className="choices">
Target Word: {this.state.word}
<br />
// this will be removed eventually
<hr></hr>
<div className="radioDiv">
<form>
<div className="word1Div">
<label>
<input
type="radio"
value={this.state.wordChoice1.id}
checked={this.state.userChoice === this.state.wordChoice1}
className="radioButton"
onChange={(event) => this.handleRadioClick(event)}
/>
{this.state.wordChoice1.word}
</label>
</div>
<div className="word2Div">
<label>
<input
type="radio"
value={this.state.wordChoice2.id}
checked={this.state.userChoice === this.state.wordChoice2}
className="radioButton"
onChange={(event) => this.handleRadioClick(event)}
/>
{this.state.wordChoice2.word}
</label>
</div>
<div className="word3Div">
<label>
<input
type="radio"
value={this.state.wordChoice3.id}
checked={this.state.userChoice === this.state.wordChoice3}
className="radioButton"
onChange={(event) => this.handleRadioClick(event)}
/>
{this.state.wordChoice3.word}
</label>
</div>
</form>
</div>
<div className="submitDiv">
<button onClick={this.handleSubmit}>Submit</button>
</div>
</div>
</div>
</div>
);
}
}
export default App;
解决方案
当您使用受控输入时,您需要在单选输入中手动设置选中的属性,将其值与状态进行比较,如下所示:
checked={this.state.userChoice === this.state.wordChoice1.id}}
在增加额外的复杂性之前,尝试进一步简化您的代码以使收音机正常工作。
推荐阅读
- html - 如何在其背景图像上垂直居中 h1 文本?
- excel - 我正在尝试搜索单元格标题 UPC,然后在 UPC 右侧添加 4 列具有特定名称
- arrays - 将 char 输入值与数组值进行比较
- flutter - Flutter,Firebase ios,云消息在后台应用时不显示,仅当应用在前台时
- unit-testing - 在 Deno 中对 global.fetch 进行 Stubbing / Spy
- javascript - 我能否以编程方式检测是否发生了 CORB 错误?
- python - 希望在 python 中为棋盘游戏项目创建一个具有视觉吸引力的 10x4 二维数组
- vba - 通过循环重构涉及 With 关键字的 VBA 脚本以减少代码长度
- typescript - 如何在 Typescript 中声明类型化对象变量
- javascript - 使用来自 firebase 的多个 id 获取数据