I am trying a very basic code in react.js :
File index.php has :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<div id="root"></div>
<!-- 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 type="text/javascript" src="my.js"></script>
</body>
</html>
Javascript file my.js
has :
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
'<h1>Hello, {formatName(user)}! </h1>'
);
ReactDOM.render(
element,
document.getElementById('root')
);
But as output I get raw JS code instead of JS being rendered:
<h1>Hello, {formatName(user)}! </h1>
How to make it run ?
EDIT:
You can find the running code in codepen here. The element
variable is declared as :
const element = <h1>Hello, {formatName(user)}!</h1>;
But I used single quotation around the element as otherwise I see error in the browser console:
Uncaught SyntaxError: Unexpected token '<'
Edit2: Fixed the codepen link. New link is this.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…