【问题标题】:React not replacing content in div反应不替换 div 中的内容
【发布时间】:2019-01-26 01:07:12
【问题描述】:

我正在尝试基本的 react 应用程序,并且正在尝试运行 react。 index.ejs 中有一个包含内容的 div 标签。最初,我在 server.js 文件中将内容设置为“...”。当我添加反应代码时,在源文件夹中的 index.js 文件中,显示在 div 标签中的值应该会改变,但事实并非如此。请帮忙

server.js:

import config from './config';
import apiRouter from './api';
import express from 'express';
import fs from 'fs'
const server = express();

server.set('view engine','ejs');

server.get('/',(req,res) => {
      res.render('index', {
    content: '....'
});
});
server.use('/api', apiRouter);
server.use(express.static('public'));

server.listen(config.port,() => {
    console.info('Express listening on port', config.port)
});

index.ejs:

<%- include('header') -%>
<div id ="root"><%- content -%></div>
<%- include('footer') -%>

header.ejs:

<!doctype html>
<html>
<head>
    <title>Hello EJS+</title>
    <meta name="description" content="">
    <meta name="keywords" content="">
</head>
</html>

页脚.ejs:

<script type="/bundle.js" charset="utf-8"></script>
</body>
</html>

index.js:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
    React.createElement('h2',null,'Hello React'), 
    document.getElementbyId('root') 
 );

【问题讨论】:

  • 您是否使用react-dom 将您的应用程序渲染为“root”?
  • 我是,在我的帖子中添加了反应代码

标签: javascript reactjs


【解决方案1】:

正确的是 document.getElementById('root')。

如果仍然无法正常工作,请检查您的 index.js 和 'react'/'react-dom' 库文件是否正在页面 (bundle.js) 中加载。

另外,请务必在浏览器的开发人员工具中检查控制台是否存在前端错误。

【讨论】:

  • 我将其更改为 document.getElementById('root') 并检查了 index.js 文件。我正在加载 lib 文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多