[英]how to pass function variable from one file to another in react
I'm doing a quiz application where I have the final score in a function in app.js, now I want to draw a graph based on user result(show in bar graph like 6 right,4 wrongsomething like that), so I wrote a function to plot the graph in another file(chart.js) using chart.js 2. the thing is I'm not able to pass the final score from app.js to chart.js.我正在做一个测验应用程序,我在 app.js 中的一个函数中获得了最终分数,现在我想根据用户结果绘制一个图形(在条形图中显示 6 对,4 错误类似),所以我写了使用chart.js 2 在另一个文件(chart.js) 中绘制图形的函数。问题是我无法将最终分数从app.js 传递到chart.js。 at the end I want to show that graph also.最后我也想展示那个图表。 note:I have used line chart for this, just to check whether my value is passing or not.注意:我为此使用了折线图,只是为了检查我的值是否通过。 App.js应用程序.js
export default function App() { return ( <div className='app'> {showScore ? ( <div className='score-section'> You scored {score} out of {questions.length} <LineChart/> </div> ) : ( ) ) }
chart.js图表.js
import React from 'react';
import {Line} from 'react-chartjs-2'
import App from '../App'
//import {score} from '../App'
//import {myExport} from '../App'
export default function LineChart()
{
//console.log(App.score);
const data = {
labels:['jan','feb','march','april'],
datasets:
[
{
label:"sales",
data:[10,7,9]
}
]
}
return(
<div>
<Line data= {data}/>
</div>
)
}
Just pass your score and question count as a prop to your LineChart component.只需将您的分数和问题计数作为道具传递给您的 LineChart 组件。
{showScore ? (
<div className='score-section'>
You scored {score} out of {questions.length}
<LineChart
score={score}
question_count={questions.length}
/>
</div>
) :
Then in your LineChart component, you can access them as然后在您的 LineChart 组件中,您可以将它们作为
this.props.score
this.props.question_count
Yannick is right.雅尼克是对的。 i have to pass it as a prop.我必须将它作为道具传递。 i made a mistake, in app.js LineChart function I passed it like Linechart(score), it should be Line chart({score}).我犯了一个错误,在 app.js LineChart 函数中我像 Linechart(score) 一样传递它,它应该是 Line chart({score})。 corrected code is.更正的代码是。
//App.js <LineChart score={score} total={questions.length} />
//Chart.js export default function LineChart({score,total}) and you can use score and total anywhere in you're function body.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.