reactjs 如何打开一个新的标签页上点击一个按钮的React?我想发送一些数据到该页也

mspsb9vt  于 2023-01-17  发布在  React
关注(0)|答案(6)|浏览(189)

我正在做一个提高发票页面,用户可以点击一个按钮提高发票,我会调用一个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;
kr98yfug

kr98yfug1#

既然你要发送大数据,把它们附加到你的目标URL看起来很破旧。我建议你使用“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
}

在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
}
rsl1atfo

rsl1atfo2#

您可以只使用普通的JS来完成它,然后用它附加一些查询参数

raiseInvoiceClicked(){
    const url = 'somesite.com?data=yourDataToSend';
    window.open(url, '_blank');
}
ifmq2ha2

ifmq2ha23#

除了在onclick方法中调用raiseInvoiceClicked()函数之外,您还可以尝试

onClick="window.open('your_url')"

在您的代码中。

vngu2lb8

vngu2lb84#

简单地做到这一点!

const openLinkInNewTab = ( url ) => {
  const newTab = window.open(url, '_blank', 'noopener,noreferrer');
  if ( newTab ) newTab.opener = null;
}
//...

  return (
         //...
         <button onClick={ () => openLinkInNewTab('your.url')}> Click Here </button>
         //...
        )
mmvthczy

mmvthczy5#

您可以使用以下代码在新窗口中打开它。

请注意,对于props,您可以传递任何应在新窗口中呈现的子组件。

const RenderInWindow = (props) => {
  const [container, setContainer] = useState(null);
  const newWindow = useRef(null);
useEffect(() => {
    // Create container element on client-side
    setContainer(document.createElement("div"));
  }, []);

  useEffect(() => {
    // When container is ready
    if (container) {
      // Create window
      newWindow.current = window.open(
        "",
        "",
        "width=600,height=400,left=200,top=200"
      );
      // Append container
      newWindow.current.document.body.appendChild(container);

      // Save reference to window for cleanup
      const curWindow = newWindow.current;

      // Return cleanup function
      return () => curWindow.close();
    }
  }, [container]);

  return container && createPortal(props.children, container);
};
yacmzcpb

yacmzcpb6#

使用 prop 传递此数据:

let href = '...url_to_redirect...'; let data_to_send = [...];

let api_href = '...url_api_where_sent_data.../?data_to_send';
export const DictDefaultOptions = (url=(api_href), method='GET') => {
let defaultOptions = {
    url : url,
    method  : method,
    mode : 'cors',
    headers : {'Access-Control-Allow-Origin':'*'}
};

return defaultOptions };

let sentData = { 
    method: defaultOptions.method, 
    mode: defaultOptions.mode 
};

send_data_to_api = () => {
    let api_return = await fetch(api_href, sentData)
        .then(response => response.json())
        .then(responseText => { 
            data = (JSON.parse(JSON.stringify(responseText))) 
        })
        .catch(error => { 
            console.log(`${requestURL} error: `, error)
        });

    do { await this.wait(100) } while(Object.keys(api_return).length <= 0);

    if (Object.keys(api_return).length > 0) {
        return window.open(href, "_blank")
    } 
};

相关问题