簡體   English   中英

在 REACT js 中渲染 DOM 元素

[英]Render DOM element in REACT js

我在本地安裝了新的 react js:

npm install -g create-react-app
create-react-app hello-world
cd hello-world
npm start

應用程序.js:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ReactDOM from 'react-dom';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>

        </div>
        <div id="root"></div>
        <div id="test"></div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>

      </div>
    );
  }
}

ReactDOM.render(
  <h1>Hello, world Root!</h1>,
  document.getElementById('root')
);

ReactDOM.render(
  <h1>Hello, world Test!</h1>,
  document.getElementById('test')
);

export default App;

索引.html:

    <body>
    <div id="root"></div>
    <div id="test"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start`.
      To create a production bundle, use `npm run build`.
    -->
  </body>
  • 問題是我只能打印 Hello, world Test! 而不是你好,世界根! 雖然我沒有收到任何錯誤也意味着它是一個 DOM 元素,而不是我沒有收到任何東西。 我也檢查了它,他們也沒有渲染。

  • 還有一件事我在index.html中添加了id為'test'的div,所以這是在其中添加div的好方法。

  • 我是 React 的新手,請提供任何幫助。

回答你的問題:

render 已經代表 ReactDOM.render,是一回事,所以在教程中,就像

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

這與

render() {
  return (
    <h1>Hello, world!</h1>
  )
}

React 小教程:是一個沒有 state 和 props 的純 HTML,我猜你就是這樣做的。

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ReactDOM from 'react-dom';

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>

        <div id="root">
          <h1>Hello, world Root!</h1>
        </div>

        <div id="test">
          <h1>Hello, world Test!</h1>
        </div>

        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

要使用狀態/道具,您可以執行以下操作:

狀態

constructor() {
  super();
  this.state = {
    text: "Hello, world Root!"
  };
}

將文本替換為:

<div id="test">
  <h1>{this.state.text}</h1>
</div>

同樣,如果你有 props = "Hello, world Root!",你可以:

道具

<div id="root">
  <h1>{this.props.root}</h1>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM