[英]how to pass function variable from one file to another in react
我正在做一個測驗應用程序,我在 app.js 中的一個函數中獲得了最終分數,現在我想根據用戶結果繪制一個圖形(在條形圖中顯示 6 對,4 錯誤類似),所以我寫了使用chart.js 2 在另一個文件(chart.js) 中繪制圖形的函數。問題是我無法將最終分數從app.js 傳遞到chart.js。 最后我也想展示那個圖表。 注意:我為此使用了折線圖,只是為了檢查我的值是否通過。 應用程序.js
export default function App() { return ( <div className='app'> {showScore ? ( <div className='score-section'> You scored {score} out of {questions.length} <LineChart/> </div> ) : ( ) ) }
圖表.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>
)
}
只需將您的分數和問題計數作為道具傳遞給您的 LineChart 組件。
{showScore ? (
<div className='score-section'>
You scored {score} out of {questions.length}
<LineChart
score={score}
question_count={questions.length}
/>
</div>
) :
然后在您的 LineChart 組件中,您可以將它們作為
this.props.score
this.props.question_count
雅尼克是對的。 我必須將它作為道具傳遞。 我犯了一個錯誤,在 app.js LineChart 函數中我像 Linechart(score) 一樣傳遞它,它應該是 Line chart({score})。 更正的代碼是。
//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.