簡體   English   中英

導出 React.JS 變量並在其他文件中使用

[英]Export React.JS variable and use in other file

所以我想做的是從Forecast.js的單選按鈕(公制英制)中獲取輸入,在Conditions.js的 function 中使用它們來確定它是熱的還是冷的。 我已經從Forecast.js導出了變量單元,但是當我嘗試在衣服() function 中使用它時它不起作用。 我已經嘗試了我在網上找到的所有東西,我試圖理解,但我是 Reactjs 的新手。

條件.js https://pastebin.com/RHbLuqZD

import { unit } from '../Forecast/Forecast.js';

function clothes(t) {
    if (unit === "metric") {
        if (Number('t') <= 20)
            return (<>
                <img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
            It's cold, dress accordingly!
            </>);
        else
            return (<>
                <img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
            It's Warm, dress accordingly!
            </>);
    }

    if (unit === "imperial") {
        if (Number('t') <= 70)
            return (<>
                <img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
            It's cold, dress accordingly!
            </>);
        else
            return (<>
                <img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} />
            It's Warm, dress accordingly!
            </>);
    }
}

Forecast.js https://pastebin.com/wcBu8bwA

export default Forecast;
export let unit = this.state.unit;

它不起作用的原因可能是因為我沒有正確執行導入和導出,或者因為我沒有正確使用導入的變量。

編輯:正如我指定的那樣,我是初學者,我知道的不多,我想要的是看看如何解決問題,然后了解如何去做。 我只需要了解我的代碼或替代方法的問題。

  1. if('clothes' 和 'Forecast' 是父子關系)

    “單位”state,可以通過“道具”交付

function Parent(props){
const [unit,setUnit] = useState("")
return(
 <Child unit={unit}>
)
}
   
function Child(props){
  console.log(props.unit)
return(
<div/>
)
}

  1. 別的。 你可以了解'react-redux'

這不是整個事情的運作方式。 一個組件中的一個 state 變量類似unit不能這樣導出。

您可以做的主要有兩件事:

  • 一種是將此unit值作為道具傳遞給Conditions.js ,然后將其傳遞給clothes function(使用時,就像您傳遞溫度值一樣)使用它;
  • 另一種是擁有 state 管理工具,例如ReduxreactN甚至使用React 的內置 context 如果您只需要使用其中之一,它可能無法補償額外的樣板,但至少值得學習它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM