如何在单击按钮时在新选项卡中打开页面,我想将一些数据发送到该页面

Man*_*a B 11 reactjs react-router

我正在加注发票页面,用户可以在点击按钮时提出发票,我会拨打api电话,在收到回复后我想将一些数据发送到页面(RaisedInvoice.jsx),这应该是在新标签中打开,我该怎么做.我没有得到的是如何在单击ReactJs中的按钮时在新选项卡中打开页面.

RaiseInvoice.jsx:

import React from 'react';
import Links from './Links.jsx';
import history from './history.jsx';

import axios from 'axios';

class RaiseInvoice extends React.Component {

    constructor(props) {
        super(props);

        // This binding is necessary to make `this` work in the callback
        this.state = {projects: [], searchParam : ''};
        this.raiseInvoiceClicked = this.raiseInvoiceClicked.bind(this);
    }

    raiseInvoiceClicked(){
        // here i wish to write the code for opening the page in new tab.
    }

    render() {
      return (
         <div>
              <Links activeTabName="tab2"></Links>
              <div className="container">
                  <div className = "row col-md-4">
                      <h1>Raise Invoice...</h1>
                  </div>
                  <div className = "row col-md-4"></div>
                  <div className = "row col-md-4" style ={{"marginTop":"24px"}}>
                      <button type="button" className="btn btn-default pull-right" onClick={this.raiseInvoiceClicked}>Raise Invoice</button>
                  </div>

              </div>
         </div>
      )
    }
}

export default RaiseInvoice;
Run Code Online (Sandbox Code Playgroud)

小智 16

由于您要发送大数据,将它们附加到目标网址看起来很破旧.我建议你为此目的使用'LocalStorage'.所以你的代码看起来像这样,

raiseInvoiceClicked(){
   // your axios call here
   localStorage.setItem("pageData", "Data Retrieved from axios request")
   // route to new page by changing window.location
   window.open(newPageUrl, "_blank") //to open new page
}
Run Code Online (Sandbox Code Playgroud)

在您的RaisedInvoice.jsx中,从本地存储中检索数据,如下所示,

componentWillMount() {
  localStorage.pagedata= "your Data";
  // set the data in state and use it through the component
  localStorage.removeItem("pagedata");
  // removing the data from localStorage.  Since if user clicks for another invoice it overrides this data
}
Run Code Online (Sandbox Code Playgroud)

  • 仅当链接不是指向其他站点时这才有效 (2认同)

Joe*_*oey 10

你可以使用普通的JS来做它并用它附加一些查询周界

raiseInvoiceClicked(){
    const url = 'somesite.com?data=yourDataToSend';
    window.open(url, '_blank');
}
Run Code Online (Sandbox Code Playgroud)


小智 6

而不是在 onclick 方法中调用 raiseInvoiceClicked() 函数,您可以尝试

onClick="window.open('your_url')"
Run Code Online (Sandbox Code Playgroud)

在你的代码中。