javascript - 数字之间的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;
}
解决方案
您的渲染功能应该是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 功能——还有更好的选择。
推荐阅读
- c# - 返工 linq 查询以返回嵌套对象
- python - 如何检查csv文件中的值是否存在于另一个文件中
- angular - ngModelChange 输入上的无限循环
- c# - “您正在寻找的资源(或其依赖项之一)”错误 WCF REST
- c++ - C++ 从 std::string 中删除所有非数字字符
- node.js - 如何缩短 nodejs、puppeteer 上的代码?
- javascript - 如果我需要在它之后设置状态,如何对 React 组件中服务器的失败响应做出反应?
- sqlite - sqlite3 如何更新从另一列获取部分值的列
- azure-cosmosdb - 用于存储和处理 Graph 数据的 CosmosDB Gremlin API 替代方案
- ios - ios objective-c 中的 uitableviewcell 内的一侧角半径问题