programing

응답으로 버튼을 클릭할 때 새 탭에서 페이지를 여는 방법나도 그 페이지로 데이터를 보내고 싶다.

easyjava 2023. 3. 20. 23:41
반응형

응답으로 버튼을 클릭할 때 새 탭에서 페이지를 여는 방법나도 그 페이지로 데이터를 보내고 싶다.

사용자가 버튼을 클릭하면 청구서를 작성할 수 있는 청구서 페이지를 작성하고 있습니다.API 콜을 호출하여 응답을 받은 후 페이지로 데이터를 보내고 싶습니다(Raised).Invoice.jsx)는 새로운 탭에서 열립니다.어떻게 하면 좋을까요?ReactJs의 버튼을 클릭해서 새로운 탭에서 페이지를 여는 방법이 이해가 되지 않습니다.

Raise Invoice.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;

빅데이터를 보내려고 했으니 타겟 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
}

인크리즈Invoice.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
}

플레인 JS를 사용하여 이를 수행하고 쿼리 주변 몇 개를 추가할 수 있습니다.

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

인상 호출 대신온클릭 메서드 내의 Invoice Clicked() 함수를 사용해 보십시오.

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

당신의 코드로.

이렇게 하면 돼!

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>
         //...
        )

다음 코드를 사용하여 새 창에서 열 수 있습니다.

소품의 경우 새 창 안에 렌더링해야 하는 모든 하위 구성 요소를 전달할 수 있습니다.

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);
};

이 데이터를 소품으로 전달합니다.

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")
    } 
};

언급URL : https://stackoverflow.com/questions/47406344/how-to-open-a-page-in-new-tab-on-click-of-a-button-in-react-i-want-to-send-some

반응형