簡體   English   中英

React Native:復選框對點擊沒有反應

[英]React Native: Checkbox not reacting to click

大家好,我正在嘗試使用復選框在 React Native 中制作測驗應用程序,我有一個問題組件,但是當用戶單擊復選框時,我似乎無法更改復選框的值。

這是我的示例代碼,您可能會指出,我做錯了什么:

測驗組件


import React, { Component } from 'react';
import { View Image, CheckBox} from 'react-native';
import { Text } from 'react-native-elements';

import questions from '../assets/questions.json';


class Quiz extends Component {



    constructor() {
        super();
        this.state = {};
        this.question = questions[0].question;
        this.answers = Object.entries(questions[0].answers).map(([key, value], index) => {
            this.state[key] = false;
            return  <View key={index}>
                        <Text>{ value } {  this.state[key].toString() }</Text>
                        <CheckBox value= { this.state[key] } onChange={() => this.checkboxClicked(key) } />
                    </View>
        });

    }

    checkboxClicked = (key) => {
          this.setState({ a: true })
    }

    render() {
        return (<View>
                      <Text h4>{ this.question} </Text>
                      { this.answers }
                </View> );
    };

};


export default Quiz;


問題 JSON:

[
    {
        "question": "Who is the strongest?",
        "answers": {
            "a": "Superman",
            "b": "The Terminator",
            "c": "Waluigi, obviously"
        },
        "correctAnswer": "c"
    },
    {
        "question": "What is the best site ever created?",
        "answers": {
            "a": "SitePoint",
            "b": "Simple Steps Code",
            "c": "Trick question; they're both the best"
        },
        "correctAnswer": "c"
    },
    {
        "question": "Where is Waldo really?",
        "answers": {
            "a": "Antarctica",
            "b": "Exploring the Pacific Ocean",
            "c": "Sitting in a tree",
            "d": "Minding his own business, so stop asking"
        },
        "correctAnswer": "d"
    }
]

我試圖在用戶單擊復選框時將 state 的復選框更改為未選中並從 true 更改為 false,但是當我使用 setState 時好像什么也沒發生?

您似乎沒有使用傳遞給 onClick 處理程序的密鑰。 嘗試:

checkboxClicked = (key) => {
  this.setState({ [key]: true })
}

如果你希望它被切換:

checkboxClicked = (key) => {
  this.setState({ [key]: !this.state[key] })
}

暫無
暫無

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

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