简体   繁体   中英

How do I pass callback function to a React component from an existing web page?

Say I have a React component with a button in it and I want to integrate this component into an existing web page (not built with React). Every time the button is clicked, I want to change some image on the web page. I wanted to somehow pass in a callback to the React component, and call the callback when the button is clicked so that the web page can decide whatever it wants to do when the button is clicked. Is this possible? If so, how should I do this? If this is not possible, what are the alternatives? Can I somehow raise an event from the component and have the web page catch it? I am new to front end development so let me know if I am crazy. :)

For example, the web page is some like:

<html>
    <head>
        <title>Some title</title>
    </head>
    <body>
        <image src="someURL"></image>
        <div id="app"></div>
    </body>
    <script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script type="text/babel" src="theReactComponent.jsx"></script>
</html>

In theReactComponent.jsx:

import React from "react";
import { render } from "react-dom";
import App from "./App";
render(<App/>, document.getElementById("app"));

In app.jsx:

import React from "react"
export default function App(): JSX.Element {
    const onClick = () => {
        // Call the callback function here to change the image in the html
    }

    return <button onClick={onClick}>Click here</button>;
}

So what I want to do is passing a call back to the component App.

It's not ideal (meaning, only very specific use cases call for this) but you can access any DOM element in the page using the standard JavaScript API from inside a React app as long as that element is present in the page at the time you want to interact with it. For example, for changing the src attribute of the img tag in your example:

import React from "react"

export default function App(): JSX.Element {
    const onClick = () => {
      const image = document.getElementById('image-id');
      image.src = 'new-src';
    }

    return <button onClick={onClick}>Click here</button>;
}

Just remember to add either an id or class attribute to your DOM element.

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