【问题标题】:React button does not show up反应按钮不显示
【发布时间】:2023-04-09 12:45:01
【问题描述】:

我是 React 的初学者,正在努力学习和改进,这里我有一个需要单击的按钮,然后应该会出现一堆数字,例如 1:1 1:2 1:3,但是在这里我似乎有问题,我的按钮没有出现,只有来自 URL 的数字出现,而且我的按钮也有 css,当刷新页面时 css 工作仅 1 秒然后消失,我没有收到任何错误留言...

代码如下:

import React, { Component } from 'react'

class Button extends Component {
    componentWillMount() {
        var proxyurl = "https://cors-anywhere.herokuapp.com/";
        var url = "http://*****.******.com/numbers.txt";
        fetch(proxyurl + url) // https://cors-anywhere.herokuapp.com/https://example.com
            .then(response => response.text())
            .then(contents => document.write(contents))
    }

    render() {
        return (
          <div className="whole">
            <button onClick={this.componentWillMount} >Increment</button>
          </div>
        )
    }
}

export default Button;
.whole {
  background-color: blue;
  color: red;
  margin: 50px 0;
  padding: 0px;
  text-align: center;
}

#root {
  white-space: pre;
}

英语不是我的母语,如有错误请见谅。

【问题讨论】:

    标签: javascript html css reactjs jsx


    【解决方案1】:

    componentWillMount 是组件的生命周期事件,不应该这样使用 (also it is recommended that componentWillMount is no longer used)。

    如果您希望按钮检索数据,您需要创建一个新函数并将其分配给按钮的 onClick 属性。例如:

    handleClick = () => {
        var proxyurl = "https://cors-anywhere.herokuapp.com/";
        // more code
        .then(contents => this.setState({ responseText: contents }))
    }
    
    render() {
        return (
            <div className="whole">
                <button onClick={this.handleClick}>Increment</button>
            </div>
            <div>{this.state.responseText}</div>
        );
    }
    

    【讨论】:

    • 谢谢你,这里的代码是从你的改进而来的:render() { return (
      ) } }
    • 现在说:避免使用 document.write()。什么是 document.write 的好替代品?
    • 如果您只想将数据输出到控制台,请尝试console.log
    • 我想把它展示给用户,如果我把它放到控制台上,我就能看到它。
    • 在这种情况下,您需要将响应内容分配给状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2016-06-13
    • 2020-11-11
    • 2021-09-12
    相关资源
    最近更新 更多