数字之间的ReactJS CSS白空间



im在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;
  }
  

您的渲染函数应为 pure ,请参阅https://reactjs.org/docs/react-component.html#render:

render()函数应纯净,这意味着它不会修改组件状态,每次调用时都会返回相同的结果,并且不会直接与浏览器进行交互。

您的渲染功能包含呼叫this.button。因此,每次您的组件重新租赁时,似乎只能调用一次时就提出请求。如文档所建议的,将此逻辑移至componentDidMount


现在,到您的实际问题上。您正在调用文档。Document.write将从页面上删除所有事件侦听器,并使用您提供的参数替换body 中的所有内容。假设您的root元素具有root(<div id="root">...</div>(的ID,则在您致电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功能 - 有更好的选择。

最新更新