簡體   English   中英

單擊React中的單選按鈕后無明顯變化

[英]Radio buttons not visibly changing upon click in 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}} 

在增加額外的復雜性之前,請嘗試進一步簡化代碼以使無線電正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM