Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

php - Simple HTML element in react.js code does not work in Xampp localhost

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
const element = '<h1>Hello, ' + formatName(user) + '! </h1>';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...