繁体   English   中英

如何从 ReactJS 中的多个组件中获取答案?

[英]How to get answers from multiple components in ReactJS?

我正在做一个调查项目,我有一个反应组件“问题”,一个子组件“问题选项”,有多个子组件“收音机”、“文本框”、“复选框”。 数据库中的一些问题有选项(多选)。 我想找到一种方法来收集用户回答的所有答案并将它们发送到数据库。

这是问题组件:

const Questions = () => {
    const [questions, setQuestions] = useState([])
    var game_id = localStorage.getItem('game_id')

    useEffect(() => {
        axios
        .post("http://127.0.0.1:8000/api/v1/questions/get_questions", {
            game_id: game_id
        })
    
        .then((response) => {
            const s = response.data.questions;
            setQuestions(s);
        });
        }, []);

    return (
        <div>
            <ul>
                {questions.map((question) => (
                    <div key={question.id}>
                        <li key={question.id}>{question.question} ({question.points} points)</li>
                        <QuestionOptions question_id={question.id} question_type={question.question_type_id}/>
                    </div>
                ))}
            </ul>
            <Button text={"Submit"} id={"submit_btn"}/>
        </div>
    );
};

这是 QuestionOptions 组件:

const QuestionOptions = (props) => {
    const [options, setOptions] = useState([]);
    const question_type = props.question_type;
    useEffect(() => {
        axios
        .post("http://127.0.0.1:8000/api/v1/question_options/get_options", {
            question_id: props.question_id,
        })

        .then((response) => {
            setOptions(response.data["options"]);
        });
    }, [props.question_id]);


    if(question_type === 0){
        return(
            <TextBox />
        )
    }else if(question_type === 1){
        return(
            <Radio options={options}/>
        )
    }else if(question_type === 2){
        return(
            <Checkbox options={options}/>
        )
    }
};

TextBox、Radio 和 Checkbox 组件如下所示:

import React from "react";

const TextBox = () => {
  return <input type={"text"} />;
};

export default TextBox;

所以我想得到用户回答的所有答案,如果没有回答所有问题,则禁用提交按钮。

问题组件如下所示:

  1. 你叫什么名字? .(输入在这里)

  2. 什么是你最喜欢的颜色? . 选项1 。 选项2。 选项3

实现这一目标的最佳方法是什么?

这里有两种类型的问题示例:带有保存按钮选项的问题,其他直接更新答案的问题。 单击保存按钮或在第三个问题中键入 answer 后检查console.log的输出。

let questions = [
  { q: 'How old are you?', id: 0 },
  { q: 'How many pets do you have?', id: 1 },
  { q: 'Where were you born?', id: 2, type: 'NoSaveBtn' },
];

let Question = (props) => {
  let [value, setValue] = React.useState('');
  return (
    <div>
      <div>{props.q}</div>
      <input value={value} onChange={(e) => setValue(e.target.value)}></input>
      <button
        onClick={() => {
          props.onSaveAnswer(value);
        }}
      >
        save answer
      </button>
    </div>
  );
};

let QuestionNoSaveBtn = (props) => {
  return (
    <div>
      <div>{props.q}</div>
      <input
        value={props.value || ''}
        onChange={(e) => props.onSaveAnswer(e.target.value)}
      ></input>
    </div>
  );
};
export default function App() {
  let [answers, setAnswers] = React.useState({});

  console.log(answers);
  return (
    <div>
      {questions.map((x) =>
        x.type !== 'NoSaveBtn' ? (
          <Question
            q={x.q}
            key={x.id}
            onSaveAnswer={(answer) =>
              setAnswers({ ...answers, [x.id]: answer })
            }
          />
        ) : (
          <QuestionNoSaveBtn
            q={x.q}
            key={x.id}
            value={answers[x.id]}
            onSaveAnswer={(answer) =>
              setAnswers({ ...answers, [x.id]: answer })
            }
          />
        )
      )}
    </div>
  );
}

暂无
暂无

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

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