首页 > 解决方案 > 数字之间的Reactjs css空白

问题描述

我是 Reactjs 的初学者并试图学习和改进,这里我的代码在哪里是 < h1 >test</ h1 > 并且在这下面应该出现像这样 1:1 1:2 1:3 的数字,但是 css 没有似乎可以使用它,我得到数字但没有 css,我也没有收到任何错误消息......这里有什么问题吗?编码 :

import React, { Component } from 'react'

class Button extends Component {

    state = {}



    button = () => {

        const proxyurl = "https://cors-anywhere.herokuapp.com/";
        const url = "http://*****.*****.com/numbers.txt"; 
        fetch(proxyurl + url) 
            .then(response => response.text())
            .then(contents => document.write(contents))

    }


    render() {
        return (
            <div >
                <h1>test</h1>
                <div style={{ color: 'red' }}>{this.button()}
                </div>
            </div >
        );
    }
}

export default Button;

CSS:

body {
  background: url('***.png');
  color:red;
  margin:50px 0; 
   padding:0px;
   text-align:center;

  
}

  #root {
    white-space: pre;
  }
  

标签: javascripthtmlcssreactjsjsx

解决方案


您的渲染功能应该是pure,请参阅https://reactjs.org/docs/react-component.html#render

render()函数应该是纯函数,即不修改组件状态,每次调用都返回相同的结果,不直接与浏览器交互。

您的渲染函数包含对this.button. 因此,每次您的组件重新渲染时,都会发出一个 fetch 请求,而这似乎只应该被调用一次。正如文档所建议的那样,将此逻辑移动到componentDidMount.


现在,到你的实际问题。您正在调用document.write,看来您不明白它是如何工作的。Document.write将从页面中删除所有事件侦听器,并将其中的所有内容替换body为您提供的参数。假设您有一个 ID 为root( ) 的根元素,在您调用;<div id="root">...</div>后该元素将被删除。document.write因此您的 CSS#root选择器将不再指向现有元素。

不要使用document.write,而是在组件的状态上设置内容并呈现:

import React, { Component } from "react";

export default class Button extends Component {
  state = {
    contents: null
  };

  componentDidMount() {
    const proxyurl = "https://cors-anywhere.herokuapp.com/";
    const url = "http://*****.*****.com/numbers.txt";
    fetch(proxyurl + url)
      .then(response => response.text())
      .then(contents => this.setState({ contents }));
  }

  render() {
    return (
      <div>
        <h1>test</h1>
        <div style={{ whiteSpace: "pre" }}>{this.state.contents}</div>
      </div>
    );
  }
}

如果你使用 React,你应该没有理由调用document.write,即使你这样做是为了测试或者你正在尝试实现某种页面重新加载/turbolinks 功能——还有更好的选择。


推荐阅读