简体   繁体   English

尝试理解 React

[英]Trying to make sense with React

I recently discovered React and I'm trying to understand how it works.我最近发现了 React,我正试图了解它是如何工作的。 I put this code:我把这段代码:

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <h1>Hello World</h1>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));

Super simple, but my page is blank instead of showing h1 element I suposedly rendered here.超级简单,但我的页面是空白的,而不是显示我应该在此处呈现的 h1 元素。 Can someone explain why doesn't it work and what am I missing to make it work?有人可以解释为什么它不起作用以及我缺少什么让它起作用吗?

There is also a simple element in the HTML file along with all instructed code from the React doc page: HTML 文件中还有一个简单的元素以及来自 React 文档页面的所有指示代码:

<div id="app"></div>
    <script
      src="https://unpkg.com/react@18/umd/react.development.js"
      crossorigin
    ></script>
    <script
      src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
      crossorigin
    ></script>
    <script src="index.js"></script>

Stack Snippet:堆栈片段:

 class App extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h1>Hello World</h1> </div> ); } } ReactDOM.render(<App />, document.getElementById("app"));
 <div id="app"></div> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin ></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin ></script>

I suspect you don't have anything in place to handle JSX.我怀疑你没有任何东西来处理 JSX。 Note that <App /> is invalid JavaScript syntax.请注意, <App />是无效的 JavaScript 语法。 It's a JavaScript extension called JSX .这是一个名为JSX的 JavaScript扩展 You don't have to use JSX with React , but most people do.您不必将 JSX 与 React 一起使用,但大多数人都这样做。

If you want to use JSX, you'll need to use Babel or similar to compile (aka "transpile") the JSX into calls to React.createElement .如果您想使用 JSX,则需要使用 Babel 或类似工具将 JSX 编译(也称为“transpile”)调用React.createElement Usually you do that as a build step so that what's deployed is already transpiled (and minified and bundled).通常您将其作为构建步骤来执行,以便部署的内容已经转译(并缩小和捆绑)。 There is an in-browser way of doing it with Babel Standalone , but it's (strongly) not recommended for production.有一种在浏览器中使用Babel Standalone的方法,但(强烈)不建议将其用于生产。 ( This meta question shows using Babel standalone.) 这个元问题显示独立使用 Babel。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM