Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

javascript - How to import function from another file into reactjs component?

I have a main.js file

function convertToFahrenheit(param) {
    return param * 2 + 30;
}

function convertToCelsius(param) {
    return (param - 32) * 1.8;
}

I have imported it into my component but it doesn't seem to work, I have also checked the path from devtool and this file completely exists

import React from "react";
import TemperatureInput from "./TemperatureInput.js";
import "../assets/js/main.js";

class Caculator extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            type: "c",
            temperature: 0,
        };
    }
    handleCelsiusChange = (value) => {
        this.setState({
            temperature: value,
            type: "c",
        });
    };
    handleFahrenheitChange = (value) => {
        this.setState({
            temperature: value,
            type: "f",
        });
    }
    render() {
        let valueCelsius = this.state.type === 'c' ? this.state.temperature : convertToCelsius(this.setState.temperature);
        return (
            <div id="caculator">
                <TemperatureInput type={this.state.type} changeInput = {this.handleCelsiusChange}/>
                <TemperatureInput type={this.state.type} changeInput = {this.handleFahrenheitChange} />
            </div>
        );
    }
}

export default Caculator;

what i get is

'convertToCelsius' is not defined  no-undef

How can I use this function in my component?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

export function convertToFahrenheit(param) {
    return param * 2 + 30;
}

export function convertToCelsius(param) {
    return (param - 32) * 1.8;
}

and then in your component

import { convertToCelsius } from "../assets/js/main.js";


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...