[英]How can I pass data from a React component to main file?
我在將數據從組件傳遞到主文件時遇到問題。 它是一個基本的測驗應用程序,從 api 獲取測驗對象並將數據傳遞給“問題”組件。 在主文件中,我有分數 state 來決定有多少答案是正確的。 但是,當單擊應答按鈕時,應用程序會看到組件中的值。 我想通過 state 匹配答案值和正確答案並增加分數。 這是問題組件和主文件。
export default function Question(props) {
const [flag,setFlag] = React.useState(true)
// TOGGLE BUTTON BACKGROUND COLOR WHEN BTN CLICKED
function toggleBtnBgColor(btn) {
if(flag) {
btn.target.classList.toggle("dark-bg-color")
setFlag(false)
}
}
return (
<>
<div className="question" key={props.index}>{props.question}</div>
{props.answers.map((answer,index)=> {
return (
<button key={index} onClick={toggleBtnBgColor} className="answer-button">{answer}</button>
)
})}
<hr></hr>
</>
)
}
主文件;
const [data, setData] = React.useState([])
const [score, setScore] = React.useState(0)
const [startAgain, setStartAgain] = React.useState(false)
// FETCH QUIZ DATA FROM API
const fetchData = async () => {
await fetch("https://opentdb.com/api.php?amount=5&type=multiple")
.then((response) => response.json())
.then((data) => setData(data.results))
}
React.useEffect(()=> {
fetchData()
},[])
// SHUFFLE ALGORITHM TO USE LATER
function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
// RENDER QUESTIONS
const questionElements = data.map((question, index) => {
// ANSWERS ARRAY AND SHUFFLE
let answers = [...question.incorrect_answers,question.correct_answer]
shuffle(answers)
return (
<Question key={index} index={index} question={question.question} answers={answers}/>
)
})
// CALCULATE FINAL SCORE WHEN CHECK BTN CLICKED
function calcScore() {
for(let question of questionElements) {
console.log(question.calcScore)
}
setStartAgain(true)
}
return (
<div className="question-container">
{questionElements}
<p>{startAgain && ("Your score is "+ score +"/5")}</p>
<button onClick={calcScore} className="check-button">{!startAgain ? "Check Answers" : "Restart Quiz"}</button>
</div>
)
檢查一下,我們將 function 傳遞給接收答案和索引的問題。 父級將更新一個包含所有答案的數組
https://codesandbox.io/s/black-cdn-p6lo5v?file=/src/App.js
const setAnswer = (index, answer) => {
const newAnswers = [...answers];
newAnswers[index] = answer;
setAnswers(newAnswers);
};
// RENDER QUESTIONS
const questionElements = data.map((question, index) => {
// ANSWERS ARRAY AND SHUFFLE
let answers = [...question.incorrect_answers, question.correct_answer];
shuffle(answers);
return (
<Question
key={index}
index={index}
question={question.question}
answers={answers}
setAnswer={setAnswer}
/>
);
});
如果我沒記錯的話,我知道您想更新父組件的 state。 您可以將 setState function 作為道具傳遞給子組件,如下所示:
return ( <Question key={index} index={index} question={question.question} answers={answers} updateScore ={setScore}/> )
大多數人更喜歡 redux 而不是將 setState 鈎子作為道具傳遞給孩子,但是很多時候人們將鈎子作為道具傳遞並解決了這個問題。
希望這對你有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.