我曾尝试在网络浏览器中运行此代码,但它会显示一个空白页面。你能解释为什么在网络浏览器中打开html时不呈现?我哪里错了?感谢
<DOCTYPE! html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script> <!-- react library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script><!-- special type of javascript syntax-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!-- jquery library -->
<title>My react page</title>
</head>
<body>
<div id="content"></div>
<script type="text/jsx">
var myComponent = React.createClass({
//component classes must have a render function that returns some HTML
render: function() {
return(
<h2>This is a core component</h2>
);
}
});
React.render(<myComponent />, document.getElementById('content'));
</script>
</body>
</html>
答案 0 :(得分:2)
正如@Hugo Dozois所说。 React编译名称以小写字母开头的组件,就好像它们是HTML元素一样。
React.createElement("myAnotherComponent", null)
您可以使用开发工具运行代码段以查看生成的代码。无论如何,你不应该在生产中使用JSXTransformer
作为警告说。
<DOCTYPE! html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script> <!-- react library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script><!-- special type of javascript syntax-->
<title>My react page</title>
</head>
<body>
<div id="content"></div>
<script type="text/jsx">
var myAnotherComponent = React.createClass({
render: function() {
throw new Error('Never actually called');
return (<span>test</span>)
}
});
var MyComponent = React.createClass({
render: function() {
console.log('Render MyComponent');
debugger;
return (<h2>This is a core component <myAnotherComponent /></h2>);
}
});
React.render(<MyComponent />, document.getElementById('content'));
</script>
</body>
</html>
答案 1 :(得分:0)
您遇到的问题是组件myComponent
的情况。
反应文档说明:
要呈现HTML标记,只需在JSX中使用小写标记名称:
要渲染React Component,只需创建一个以大写字母开头的局部变量:
您可以在此处阅读更多内容:https://facebook.github.io/react/docs/jsx-in-depth.html#html-tags-vs.-react-components
因此,要解决您的问题,只需将名称从myComponent
更改为MyComponent
但是,为了与其他人一致,放弃JSX Transformer并采用更新的方法将JSX编译成常规JS更为明智。有很多方法可以做到这一点:Gulp,Webpack等......找到最适合你的方法!
<DOCTYPE! html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script> <!-- react library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script><!-- special type of javascript syntax-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!-- jquery library -->
<title>My react page</title>
</head>
<body>
<div id="content"></div>
<script type="text/jsx">
var MyComponent = React.createClass({
//component classes must have a render function that returns some HTML
render: function() {
return(
<h2>This is a core component</h2>
);
}
});
React.render(<MyComponent />, document.getElementById('content'));
</script>
</body>
</html>