简体   繁体   English

ReactJS - 从浏览器调用 function

[英]ReactJS - call function from broswer

I started working with React and just converting an older web application into ReactJS.我开始使用 React,只是将旧的 web 应用程序转换为 ReactJS。

My problem is that I load some content which later is added into a modal (dangerouslySetInnerHTML).我的问题是我加载了一些内容,这些内容后来被添加到模式中(dangerouslySetInnerHTML)。 The content includes <input type="button" onclick="myFunc()">内容包括<input type="button" onclick="myFunc()">

Previously I can just write a global function myFunc() and this was executed.以前我可以只写一个全局 function myFunc() 并执行。 But with ReactJS, I don't know how to do this.但是对于 ReactJS,我不知道该怎么做。 If I just write this function into the component I get myFunc is not defined .如果我只是将这个 function 写到组件中,我会得到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.我建议使用某种 state 管理工具,例如 Context 或 Redux。 That way you can set a global function witch can be executed from anywhere in the app.这样你就可以设置一个全局 function 女巫可以从应用程序的任何地方执行。

First of all as the comment suggested, it is better to render the modal in react too instead of using dangerouslySetInnerHTML.首先,正如评论所建议的,最好在反应中渲染模态而不是使用危险的SetInnerHTML。 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.然后考虑在反应中,当项目变得非常大时,更喜欢使用 state 管理工具,如上面的答案所示。 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).如果您不考虑使用这样的工具,最佳做法是将 state 保留在元素树的顶部并将其向下传递(连同对其进行变异的函数)。 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.因此,您问题的解决方案基本上是在包含您想要变异的 state 的组件上定义 function 并将其作为道具传递。 Check this article for more info: https://reactjs.org/docs/faq-functions.html查看这篇文章了解更多信息: https://reactjs.org/docs/faq-functions.html

You can write global functions in react.你可以在 react 中编写全局函数。 Somewhere inside the class, maybe in the constructor or in componentDidMount or something, just write window.myFunc = this.myFunc.bind(this); class 内部的某个地方,可能在构造函数中或在componentDidMount中,只需编写window.myFunc = this.myFunc.bind(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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