react.js 代码中的简单 HTML 元素在 Xampp localhost 中不起作用 [英] Simple HTML element in react.js code does not work in Xampp localhost

查看:30
本文介绍了react.js 代码中的简单 HTML 元素在 Xampp localhost 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 react.js 中尝试一个非常基本的代码:

I am trying a very basic code in react.js :

文件 index.php 有:

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 文件 my.js 有:

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')
);

但作为输出,我得到原始 JS 代码而不是渲染 JS:

But as output I get raw JS code instead of JS being rendered:

<h1>Hello, {formatName(user)}! </h1>

如何让它运行?

您可以在 codepen 此处中找到运行代码.element 变量声明为:

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: 修复了 codepen 链接.新链接是this.

Fixed the codepen link. New link is this.

推荐答案

const element = '<h1>Hello, ' + formatName(user) + '! </h1>';

这篇关于react.js 代码中的简单 HTML 元素在 Xampp localhost 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆