如何在 WordPress 页面上呈现 React?

我正在尝试让 React 应用程序呈现为 Wordpress 页面的一部分。


我使用create-react-app并添加了我的应用程序


"homepage": "." 

到package.json构建之前。


首先,我通过将必要的核心文件嵌入到标准 html 文档中来尝试该功能。


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>

<body>

    


<div id="wp-root"></div>


<script src="runtime-main.363857b3.js"></script>

<script src="main.ef284662.chunk.js"></script>

<script src="2.319ef205.chunk.js"></script>


</body>

</html>

果然它起作用了!


当接近 Wordpress 时,我将脚本文件放入functions.php.


wp_enqueue_script( 'script', get_template_directory_uri() . '/js/test.js', true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/js/2.319ef205.chunk.js', true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/js/main.ef284662.chunk.js', true);

wp_enqueue_script( 'script', get_template_directory_uri() . '/js/runtime-main.363857b3.js', true);

我还在alert("test")同一文件夹中查询了一个简单的测试脚本,以确保它能够响应。


我的测试脚本按预期在每个页面上触发,因此我继续将我的测试脚本包含<div id="wp-root"> 在页面上,并将科学包含在header.phpbody 标签下


我的测试脚本有效,我的 React 构建在测试中有效index.html。


为什么 WordPress 不渲染它?


largeQ
浏览 130回答 1
1回答

烙印99

这有效!如果我将脚本从远程主机直接加载到它footer.php之前,</header>它就能完美运行!<?php wp_footer(); ?><script src="http://localhost/react_app/build/static/js/runtime-main.363857b3.js"></script><script src="http://localhost/react_app/build/static/js/main.ef284662.chunk.js"></script><script src="http://localhost/react_app/build/static/js/2.319ef205.chunk.js"></script></body>我也尝试成功导入 React CDN,但这并没有解决问题。这可能是工作方式的问题wp_enqeue_scripts。在这种情况下,它只是忽略了除test.js
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript