【问题标题】:React Native: Checkbox not reacting to clickReact Native:复选框对点击没有反应
【发布时间】:2019-10-21 19:09:31
【问题描述】:

大家好,我正在尝试使用复选框在 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"
    }
]

我试图在用户单击复选框时将复选框的状态更改为已选中并从 true 更改为 false,但是当我使用 setState 时就像没有发生任何事情一样??

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您似乎没有使用传递给 onClick 处理程序的密钥。试试:

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

    如果你想切换它:

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

    【讨论】:

    • 它不工作我无法切换复选框值:(
    • onChange 应该是 onValueChangeDocs
    • @Dhaval 我需要更多信息才能提供帮助。
    猜你喜欢
    • 2017-01-10
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2013-01-08
    • 1970-01-01
    • 2019-08-02
    相关资源
    最近更新 更多