在React中未定义MagicValue

时间:2020-05-25 01:45:13

标签: reactjs

开始学习React的前30分钟,无法编写本书的第一个示例。

<!doctype html>

<title>Hello Kansas City LOL</title>

<script src="https://unpkg.com/react@16.4.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.4.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<div id="app"></div>

<script type="text/babel">
    var anElement = {
        $$typeof:  magicValue,
        type:  "p",
        ref: null,
        props: {
            children: "Hello World From KC."
        }
    };

var renderTarget = document.getElementById("app");
ReactDOM.render(anElement, renderTarget);
</script>

它给出的错误是“ MagicValue未定义” 但是据我从书中了解到的那样,MagicValue是React的某种已知值。 那是怎么回事?

1 个答案:

答案 0 :(得分:1)

在您的代码中,typeof应该包含Symbol.for

这应该有效

<!DOCTYPE html>

<title>Hello Kansas City LOL</title>

<script src="https://unpkg.com/react@16.4.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.4.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<div id="app"></div>

<script type="text/babel">
  var anElement = {
    $$typeof: Symbol.for("react.element"),
    type: "p",
    ref: null,
    props: {
      children: "Hello World From KC.",
    },
  };

  var renderTarget = document.getElementById("app");
  ReactDOM.render(anElement, renderTarget);
</script>


您也可以使用React.createElement

进行简化

<!DOCTYPE html>

<title>Hello Kansas City LOL</title>

<script src="https://unpkg.com/react@16.4.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.4.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<div id="app"></div>

<script type="text/babel">
  var anElement = React.createElement(
    /* type */ "marquee",
    /* props */ { bgcolor: "#ffa7c4" },
    /* children */ "hi"
  );

  var renderTarget = document.getElementById("app");
  ReactDOM.render(anElement, renderTarget);
</script>