以下是React.js中最简单网页的代码。如果我在记事本中写这个并在web浏览器中以html doc形式打开它,它不应该显示“Hello World”吗?相反,浏览器不显示任何内容。 React.js需要任何其他依赖项吗?
<html lang="en">
<head>
<title>My First React Example</title>
</head>
<body>
<script src="https://fbme/react-15.1.0.js"></script>
<script src="https://fbme/react-dom-15.1.0.js"></script>
<script type="text/babel">
<div id="app"></div>
ReactDOM.render(
React.createElement('h1', null, "Hello world"),
document.getElementById('app');
);
</script>
</body>
</html>
答案 0 :(得分:2)
以下是在Firefox和Chrome中测试的功能齐全的示例。下面我分析您发布的示例存在问题的部分:
<html lang="en">
<head>
<title>My First React Example</title>
</head>
<body>
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
<script type="text/babel">
ReactDOM.render(
React.createElement('h1', null, "Hello world"),
document.getElementById('app')
);
</script>
</body>
</html>
如果您从原始示例开始并在打开网页时查看开发者控制台(在大多数浏览器上为F12),您将在第13行看到以下错误:
参数列表之后SyntaxError:missing)
由于document.getElementById('app');
之后的额外分号,发生了错误。删除:
ReactDOM.render(
React.createElement('h1', null, "Hello world"),
document.getElementById('app') // No more semicolon here
);
然后控制台将显示以下错误:
ReferenceError:未定义ReactDOM
那是因为你的脚本标签有一些嵌套问题,而且React库的fbme链接不会通过。更改为此并添加Babel库:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
现在你的例子应该可以正常工作。
答案 1 :(得分:1)
修改代码会产生所需的输出
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
ReactDOM.render(
React.createElement('h1', null, "Hello world"),
document.getElementById('app')
);
</script>
</body>
</html>
答案 2 :(得分:0)
使用babel-standalone并将React内容包装在<script src="https://fbme/react-15.1.0.js"></script>
<script src="https://fbme/react-dom-15.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
<script type="text/babel">
<div id="app"></div>
ReactDOM.render(
React.createElement('h1', null, "Hello world"),
document.getElementById('app');
);
</script>
webpack
虽然我建议您将transpiler
用作create-react-app
。您也可以使用{{1}}