简体   繁体   中英

ReactJS - call function from broswer

I started working with React and just converting an older web application into ReactJS.

My problem is that I load some content which later is added into a modal (dangerouslySetInnerHTML). The content includes <input type="button" onclick="myFunc()">

Previously I can just write a global function myFunc() and this was executed. But with ReactJS, I don't know how to do this. If I just write this function into the component I get myFunc is not defined .

Does someone have an idea of how to solve it?

Many thanks in advance

I suggest using some kind of state management tool like Context or Redux. That way you can set a global function witch can be executed from anywhere in the app.

First of all as the comment suggested, it is better to render the modal in react too instead of using dangerouslySetInnerHTML. Then consider that in react, when the project becomes really big it's prefered to use a state management tool as the answer above suggests. In case you are not considering to use a tool like this, the best practice is to keep the state on top of the element tree and pass it down (along with the functions which mutates it). So the solution to your question is basically definining the function on the component which holds the state you want to mutate and pass it down as props. Check this article for more info: https://reactjs.org/docs/faq-functions.html

You can write global functions in react. Somewhere inside the class, maybe in the constructor or in componentDidMount or something, just write window.myFunc = this.myFunc.bind(this);

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