如何在反应js中调用或将值从一个js文件传递到另一个文件

Posted

技术标签:

【中文标题】如何在反应js中调用或将值从一个js文件传递到另一个文件【英文标题】:how do I call or pass the value from one js file to another file in react js 【发布时间】:2021-09-05 18:58:58 【问题描述】:

我对 Reactjs 世界完全陌生,

如何将 exportExcelPage.js 中选定的“start_date”和“end_date”调用到 exportAPICall.js 文件中。

我在 exportExcelPage.js 中创建了日期字段,我需要将这些字段值传递给 exportAPICall.js 文件。

我试图通过如下函数: exportExcelPage.js


            startDate && endDate && 
            <Button id="button" variant="contained" size="large" className=classes.button startIcon=<CloudDownloadIcon /> onClick=exportAPICall(startDate, endDate)>
              DOWNLOAD
            </Button>
          

exportAPICall.js

export default function exportAPICall(startDate, endDate)
.............

之后能够在控制台中获取日期值,但问题是当我自动选择 endDate 时,它​​会触发 api 调用而无需单击 downlad 按钮。

请帮助我,如何在 exportAPICall.js 文件中调用这两个字段。

exportExcelPage.js

import React,  useState  from "react";

//styles
import "../../styles/App.css";
import "react-datepicker/dist/react-datepicker.css";

//imports
import DatePicker from "react-datepicker";
import addMonths from 'date-fns/addMonths';
import format from 'date-fns/format';
import exportImage from '../../images/exportImage.jpg';
import  makeStyles  from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import CloudDownloadIcon from '@material-ui/icons/CloudDownload';
import TITLE, NOTE_DESC, NOTE, START_DATE, END_DATE, DOWNLOAD from '../../utilities/text';

//api call
import exportAPICall from "../../api/exportAPICall";

const useStyles = makeStyles((theme) => (
  button: 
    margin: theme.spacing(1),
  ,
));

function ExportExcelPage() 
  const classes = useStyles();
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);

  const handleStartDate = (date) => 
    setStartDate(date);
    setEndDate(null);
  ;

  const handleEndDate = (date) => 
    setEndDate(date);
  ;


  if (startDate) 
    var maxDate = startDate;
    maxDate = format(addMonths(startDate, 36), " E MMM dd yyyy HH:mm:ss ");
    var strToDate = new Date(maxDate);
    console.log("maxDate value ==" + maxDate);
    console.log("string to date value ==" + strToDate);
  


  return (
    <div className="App" id="container">
      <div className="input-container">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"></link>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></link>
        <script src = 'header.js'></script>
        <img src=exportImage id="ui-image"></img>
        <div >
          <h4 id="title"><b>TITLE</b></h4>
          <form id="form-css">
            <DatePicker id="startDate-css" placeholderText=START_DATE dateFormat='dd-MM-yyyy' selected=startDate onChange=handleStartDate/>
            <span>   <b id="dash-space">-</b>    </span>
          <DatePicker id="endDate-css" placeholderText=END_DATE dateFormat='dd-MM-yyyy' selected=endDate minDate=startDate maxDate=strToDate onChange=handleEndDate/>
          </form>
          <p id="note"><b>NOTE</b><span id="space"></span>NOTE_DESC</p>
          
            startDate && endDate && 
            <Button id="button" variant="contained" size="large" className=classes.button startIcon=<CloudDownloadIcon /> onClick=exportAPICall>
              DOWNLOAD
            </Button>
          
        </div>
      </div>
    </div>
  );


export default ExportExcelPage;

exportAPICall.js


import  formatMs  from "@material-ui/core";
import axios from "axios";
import * as moment from 'moment';
import EXPORT_API from '../utilities/endpoints';

export default function exportAPICall()

    const current_date = moment(new Date()).format("YYYY-MM-DD_HHmmss");

    let url = process.env.REACT_APP_MS_BASEURL + EXPORT_API();

    let data = 
        auth: false,
        op: "",
        currentUser : 
    ;

    let postData = 
        "Id": 190,
        "startDate" : "2021-06-01T03:48:46.174Z",
        "endDate" : "2021-06-16T03:48:46.174Z"
    
    

    
    axios.post(url, postData,  
        withCredentials : true
        
    )
    .then(r => 
        console.log("gettoken",r);
        data.auth = true;
        data.op = r.headers['x'];
        data.currentUser = r.data;
        //dispatch(GetActionObject(loginMod.actionType+'/'+Constants.STATUS_SUCCESS, data));
        //  setGlobalState_callback(data);

     var fileURL = window.URL.createObjectURL(new Blob([r.data]));
     var fileLink = document.createElement('a');
    
     fileLink.href = fileURL;
     fileLink.setAttribute('download', 'AdminReport_'+current_date+'.zip');
     document.body.appendChild(fileLink);
     
     fileLink.click();
        
    )
    .catch(e=>
        console.log(e);
        if(e.response)
        
            data.error = e.response.data;
        
        else 
        
            data.error = e.message;
        
        //dispatch(GetActionObject(loginMod.actionType+'/'+Constants.STATUS_FAILED, data));
        //setGlobalState_callback(data);
    );  
 


export exportAPICall

【问题讨论】:

【参考方案1】:

尝试像这样调用 exportApiCall 函数,它会解决你的问题:


  startDate && endDate && 
  <Button
    id="button"
    variant="contained"
    size="large"
    className=classes.button
    startIcon=<CloudDownloadIcon />
    onClick=() =>  exportAPICall(startDate, endDate) 
  >
    DOWNLOAD
  </Button>

您需要将函数传递给 onClick 而不是调用它。当点击事件触发时,该函数将被调用。

【讨论】:

以上是关于如何在反应js中调用或将值从一个js文件传递到另一个文件的主要内容,如果未能解决你的问题,请参考以下文章

将值从一个函数传递到另一个JS

在角度js中将值从一个控件传递到另一个控件[重复]

如何将值从 JS 传递回 Python

如何将值从javascript传递到iOS UIWebView

NodeJS:将字段值从 ResolverQuery 传递到另一个 JS 文件

如何将值从一个组件传递到另一个没有父子关系的库中的组件文件?