PHP 视图文件不需要替换为 js 文件。可以使用<script>
标签轻松地将 JavaScript 添加到 PHP 文件中。下面是CodeIgniter 应用程序中的Add React in One Minute演示。
要将 React 演示集成到 CodeIgniter 中,请从一个简单的控制器开始 - React.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class React extends CI_Controller
{
public function index()
{
$this->load->view('react_view');
}
}
“视图”文件直接来自 React 演示,但它放在一个 .php 文件而不是 .html 中。
对演示代码所做的唯一更改是在页面底部的脚本标记中。我的assets
文件夹与 CodeIgniter 的/application
文件夹处于同一级别。有assets
用于 css、js 和图像的子文件夹。
/public_html
/application
/system
/assets
/js
/css
/img
所以我已经更改了src
加载的标签like_button.js
以使用我的文件布局。
“视图”文件react_view.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</p>
<p>React is loaded as a script tag.</p>
<p>
This is the first comment.
<!-- We will put our React component inside this div. -->
<div class="like_button_container" data-commentid="1"></div>
</p>
<p>
This is the second comment.
<!-- We will put our React component inside this div. -->
<div class="like_button_container" data-commentid="2"></div>
</p>
<p>
This is the third comment.
<!-- We will put our React component inside this div. -->
<div class="like_button_container" data-commentid="3"></div>
</p>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src="assets/js/like_button.js"></script>
</body>
</html>
/assets/js/like_button.js
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked comment number ' + this.props.commentID;
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
// Find all DOM containers, and render Like buttons into them.
document.querySelectorAll('.like_button_container')
.forEach(domContainer => {
// Read the comment ID from a data-* attribute.
const commentID = parseInt(domContainer.dataset.commentid, 10);
ReactDOM.render(
e(LikeButton, { commentID: commentID }),
domContainer
);
});