[英]how to rewrite plain javascript into a react component (foreach)
[英]How to call a react deployed component in plain JavaScript (like a Partial View)
我在 reactjs 中开发了一些组件。 现在我想在 JavaScript 中调用这段代码。
我已经在某处部署了反应组件。 现在我想在我的 JavaScript 代码中使用。
我们不能使用 iframe。 我们想将 reactjs 组件放在 div(quizid)中。
我正在尝试的内容如下:
<div class="row clearfix">
<div class="col-md-12" data-noedit data-module="quiz-module" data-module-desc="quiz" >
<div id='quizid'>
</div>
</div>
</div>
<script>
var docReady = function (fn) {
var stateCheck = setInterval(function () {
if (document.readyState !== 'complete') return;
clearInterval(stateCheck);
try { fn() } catch (e) { }
}, 1);
};
docReady(function () {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) { debugger;
var parser = new DOMParser();
var newNode = parser.parseFromString(xmlhttp.responseText, 'text/html');
if(newNode && newNode.documentElement){
document.getElementById('quizid').appendChild(newNode.documentElement);
}
} else {
console.log("Status error: " + xmlhttp.status);
}
}
};
xmlhttp.open("GET", "http://phpstack-444580-2225309.cloudwaysapps.com/KitchenQuestionApp/", true);
xmlhttp.send();
});
</script>
在上述方法中,整个 html 都进入 quizid div 并且不显示任何内容。
我记得,Asp.Net MVC 中有一个 Partial View 术语。 我们可以使用类似的东西吗?
react组件版本通过(package.json)开发
{
"name": "test",
"version": "0.1.0",
"private": true,
"homepage": "/KitchenQuestionApp/",
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"bootstrap": "^4.6.0",
"node-sass": "^4.14.1",
"react": "^17.0.2",
"react-bootstrap": "^1.6.1",
"react-bootstrap-range-slider": "^2.0.2",
"react-dom": "^17.0.2",
"react-icons": "^4.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"react-slick": "^0.28.1",
"slick-carousel": "^1.8.1",
"smooth-scroll": "^16.1.3",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
有没有人可以为它提出一个好的解决方案?
如果您尝试在 2 个存储库之间共享代码,我建议将共享代码移动到单独的 npm 包中并在两个地方重用它,而无需从另一个页面获取脚本。
因此,您将拥有 2 个带有 React 应用程序的存储库,并且您将使用相同的 npm 包来实现共享功能。
如果这不是您的选择,则有一个肮脏的 hack:在您的quizid
应用程序中,您检查quizid
容器是否存在(这意味着脚本在纯 JS 页面上执行)并尝试安装在那里,否则您像现在一样安装应用程序。 在您的普通 JS 页面中,您可以像现在一样从另一个页面获取脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.