【问题标题】:CDN links for React packages and how to import it when using react using the scripts from CDNReact 包的 CDN 链接以及使用 CDN 中的脚本使用 react 时如何导入它
【发布时间】:2020-01-21 05:37:30
【问题描述】:

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

<!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,而且配置也更复杂。
  • 运行 react 最简单的方法就是运行“npx create-react-app [name of your app]”命令。 create-react-app.dev
  • 我了解 create-react-app 和一堆现代工具的用法,这只是为了在使用他们的 CDN 的同时在这个简单的单个文件中测试 React,这也在 Reacts 官方页面中提到.
  • 感谢您向我澄清您的问题。我开始调查您添加的软件包并查看文档。不包括挂钩。
  • 没问题,谢谢

标签: javascript reactjs babeljs cdn


【解决方案1】:

当你使用脚本时,React 在窗口对象上暴露为React,你也使用了一个没有钩子的 React 版本(钩子在 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 值作为输入的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>

【讨论】:

  • 谢谢!更改它工作的反应版本后,你是对的,钩子是 React 16.8+ 的一部分。
  • 如何为其他cdns解构?我需要{ BrowserRouter as Router, Switch, Route, Link, Redirect, NavLink } from "react-router-dom"。有没有通用的方法?
  • @ManirajSS 添加此脚本&lt;script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"&gt;&lt;/script&gt; 它将在window.ReactRouterDOM see here 上公开包
猜你喜欢
  • 1970-01-01
  • 2018-05-09
  • 1970-01-01
  • 2019-12-29
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
  • 2017-12-06
相关资源
最近更新 更多