我是React Js的新手,对于我的项目,我开始使用React JS编写在线测试。我想将分数变量的值从Quiz.js类组件传递给Graph.js功能组件。您能帮我解决问题吗?我正在尝试很多并且卡住了。请帮助我。
Quiz.js代码:
import React, {Component} from 'react';
import { Pie } from 'react-chartjs-2';
import PieChart from './Graph';
class Quiz extends Component{
constructor(props){
super(props)
this.state={
userAnswer:null,
currentIndex:0,
options: [],
quizEnd: false,
score:0,
disabled:true,
}
}
checkStatistics(score)
{
console.log('in check statistics function')
this.setState(
{
score: score
}
)
// this.props.navigation.navigate("/Graph", {score })
// window.location.href = "/Graph";
window.location.href = 'http://localhost:3000/Graph?score=${score}';
}
render()
{
const {question,options,currentIndex,userAnswer,quizEnd}= this.state
if(quizEnd){
return(
<div className="containerBox">
<h1> Game Over. Final score is {this.state.score} points</h1>
<p> The correct answers for the quiz are</p>
<ul>
{QuestionBank.map((item,index) => (
<li className='options'
key={index}>
{item.answer}
</li>
))}
</ul>
{currentIndex===QuestionBank.length-1 &&
<button className="attemptButton" onClick={this.attemptAnotherTry} disabled= {this.state.disabled}>
Retest?
</button>
}
{currentIndex===QuestionBank.length-1 &&
<button onClick={this.checkStatistics.bind(this, this.state.score)}>Check Statistics</button>}
</div>
)
}
}
}
export default Quiz;
Graph.js代码
import React, {useState, useEffect} from 'react';
const PieChart = (props) =>
{
const [chartData,setChartData]= useState({})
const chart = () =>{
setChartData({
labels: ['Correct Answers', 'Incorrect Answers'],
datasets:[
{
label: 'statistical chart',
data:[props.score,2],
backgroundColor: ['rgba(255,99,132,1)',
'rgba(255,205,86,1)'],
borderWidth: 4
}
]
})
}
useEffect(()=>
{
chart()
},[])
return(
<div>
<div style={{width:'1000px', height:'1000px',textAlign:"center",marginLeft:'250px'}}>
<Pie data={chartData}/>
<Link to="/Test" style={{textAlign:"center"}}>Attempt test again</Link>
{/* <Pie data={this.getChartData}/> */}
</div>
</div>
)
}
export default PieChart;