简体   繁体   English

单击React中的单选按钮后无明显变化

[英]Radio buttons not visibly changing upon click in React

I have a React site with radio buttons. 我有一个带有单选按钮的React网站。 When a button is clicked, it records the correct value to state, but the button itself does not change to indicate it has been clicked. 单击按钮时,它会记录正确的状态值,但是按钮本身不会更改以表明已被单击。

Furthermore, when a user clicks the Submit button, it executes the !== action in handleSubmit, even if the user selected the correct answer. 此外,当用户单击“提交”按钮时,即使用户选择了正确的答案,它也会在handleSubmit中执行!==操作。

GitHub: https://github.com/irene-rojas/word-guess GitHub: https : //github.com/irene-rojas/word-guess

I cannot find the disconnect that is preventing it from working. 我找不到阻碍其正常工作的断开连接。

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;

When you use controlled inputs you need to manually set the checked property in the radio input, comparing its value to the state, like this: 使用受控输入时,需要在单选输入中手动设置选中的属性,将其值与状态进行比较,如下所示:

checked={this.state.userChoice === this.state.wordChoice1.id}} 

Try simplifying your code a lot more to get the radio to work before adding the additional complexity. 在增加额外的复杂性之前,请尝试进一步简化代码以使无线电正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM