简体   繁体   中英

Third Party script not consistently find button with certain id in react component

I am creating a web app that incorporates a third party (NMI) to collect payment information. The script that NMI provides does all the work all that has to be done is add a html button with an id of 'payButton' and when that button is clicked a popup is presented to collect CC info.

Below is the only situation that I am able to get it to work.

<html lang="en">
  <head>

    <!-- Other imports -->

    <!--
      NMI Collect.js script
    -->
    <script src="https://secure.networkmerchants.com/token/Collect.js" data-tokenization-key="security_key"></script>

    <title>React App</title>
  </head>
  <body></body>
</html>
class App extends Component {

    render() {
        return (
            <div>
                <button type="button" id="payButton">Pay $5</button>
            </div>
        )
    }
}

Now the code above works just fine. I can click the button and the popup opens like it should but when I want to hide or show the button based on state of the component the popup fails to work. The code below is this situation not working.

class App extends Component {

    render() {
        const test = false

        let data
        if(test) {
            data = <div></div>
        } else {
            data = <button type="button" id="payButton">Pay $5</button>
        }

        return (
            <div>
                {data}
            </div>
        )
    }
}

The script is most likely looking for the button and adding a listener directly on it. That means that as soon as some state changes that would hide the button, the button is being removed from the DOM and the listener is lost with it.

You'll need to check the NMI api to see what options you have. If there's a manual way to reattach the listener, you could do that whenever the component updates and the button is shown again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM