React 包的 CDN 链接以及在使用来自 CDN 的脚本进行反应时如何导入它

CDN links for React packages and how to import it when using react using the scripts from CDN

我在没有 NPM 和其他工具的情况下尝试使用 React,而是通过添加 CDN links 来使用它, 但是如何导入依赖包,例如 useState 钩子?如果它是通过另一个脚本标签添加的,那么 CDN link 是什么?下面是我的代码,

<!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>React Local</title>
  <script type="application/javascript" src="https://unpkg.com/react@16.0.0/umd/react.production.min.js"></script>
  <script type="application/javascript" src="https://unpkg.com/react-dom@16.0.0/umd/react-dom.production.min.js"></script>
  <script type="application/javascript" src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
</head>

<body>
  <div id="root"></div>

   <script type="text/babel">
    const rootElement = document.getElementById('root') 

    const App = (props) => { 
    const [text, setText] = useState('hello'); 
        return (
            <div>
            <h1>{text}</h1>
            <input type="text" onClick={(e) => setText(e.target.value)}> </input>
            </div>
        );
    }

    ReactDOM.render(<App />, rootElement)
  </script>

</body>
</html>

这里会报错,useState没有定义。
注意:这只是为了使用直接添加到 html 文件中的 CDN 脚本来测试 React,尽管我知道 create-react-app 和现代工具

当您使用脚本时,React 在 window 对象上公开为 React,您还使用了没有 hooks 的 React 版本(hooks 在 16.8 中发布)

将您的脚本更新为(您可能希望使用开发脚本以获得更好的错误消息)

<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

如果你想访问 useStateReact 解构它或使用 React.useState

此外,对于输入更改事件使用 onChange 而不是 onClick 以及使用来自状态的 text 值作为输入 [=20] 的 value =]

<script type="text/babel">
  const { useState } = React

  const App = (props) => { 
    const [text, setText] = useState('hello');

    return (
      <div>
        <h1>{text}</h1>
        <input type="text" value={text} onChange={(e) => setText(e.target.value)} />
      </div>
    );
  }

  const rootElement = document.getElementById('root')
  ReactDOM.render(<App />, rootElement)
</script>