我有一个提供给客户的 EJS 视图:
索引.ejs
<!DOCTYPE html>
<html>
<head>
<title>Example app</title>
</head>
<body>
<div id="reactApp">
<%- reactContent %>
</div>
</body>
<script src="__res__/client/main.bundle.js" />
</html>
main.bundle.js
是我使用 browserify 创建的包:
gulpfile.js(部分)
function bundle(filename) {
var bundler = browserify('./app/client/' + filename + '.js');
bundler.transform(babelify);
bundler.transform(reactify);
return bundler.bundle()
.pipe(source(filename + '.bundle.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./dist/client'));
}
最终为客户提供以下代码:
main.js(捆绑到 main.bundle.js 中)
import React from 'react';
import {Login} from './auth/login.react';
React.render(React.createElement(Login), document.getElementById('reactApp'));
alert('hi');
但是,即使浏览器请求并接收main.bundle.js
脚本,客户端也不运行该alert('hi');
行,这使我相信该React.render
行也不起作用。我可以确认 Javascript 已启用,并且我的浏览器是最新版本的 Chrome。我的反应组件(Login
)如下:
login.react.js
import React from 'react';
export class Login extends React.Component
{
handleClick() {
alert('Hello!');
}
render() {
console.log('rendered');
return (
<button onClick={this.handleClick}>This is a React component</button>
);
}
}
所以,很简单。但是,您在代码中看到的任何警报都不会运行。该console.log('rendered');
行从未在服务器上运行,但是当我检查页面的源代码时,我得到:
我的页面的 HTML 输出
<!DOCTYPE html>
<html>
<head>
<title>Example app</title>
</head>
<body>
<div id="reactApp">
<button data-reactid=".2fqdv331erk" data-react-checksum="436409093">Lel fuck u</button>
</div>
</body>
<script src="__res__/client/main.bundle.js" />
</html>
这意味着服务器正确地呈现了我的反应组件,但是为什么客户端脚本不起作用?该handleClick
函数永远不会运行,我的console.log
线路永远不会运行,线路也不会运行alert
。怎么了?reactid 和校验和正确呈现,它不应该工作吗?客户端的 React 代码不应该足够聪明地找到组件并正确运行吗?