【问题标题】:Check a div value and update a class in React检查 div 值并更新 React 中的类
【发布时间】:2020-04-16 02:38:06
【问题描述】:

它将成为应用仪表板的一部分。它将从 API 接收一个数字作为字符串,这部分仍有待实现。可能是axiosonComponentDidMount 的电话。

我想根据其值设置一些特定颜色的数字文本。我正在读取页面加载时的数值和onChange,然后设置一个引导类。我正在使用React 在 Ionic 中开发。

this.state = {
    warningColor: true
}

componentDidMount() {
    var delayed: HTMLElement | null = document.querySelector("#delayed");
    if (delayed != null && delayed.textContent === "0") {
        this.setState({ warningColor: false })
    }
}

handleAlerts() {
    var delayed: HTMLElement | null = document.querySelector("#alert");
    if (delayed != null && delayed.textContent == "0") {
        this.setState({ warningColor: false })
    } else {
        this.setState({ warningColor: true })
    }
}

<div id="alert" className={"number " + (this.state.warningColor ? "text-warning" : "text-success")} onChange={this.handleAlerts}>0</div>

是否有更好/更清洁的方法来检查值并在div 中设置类?

【问题讨论】:

  • 变化发生在哪里?你不能设置值抛出状态吗? this.state = { warningColor: true, alerVal:0 } 并在更改时更改状态?
  • 警报数量何时会改变?你在那里有一个静态的0;应用程序的其他部分是否会执行alert.textContent = "X"?并致电onChange?这似乎很不雅;警报的数量应该作为道具传递给组件。
  • 静态值0,不能在应用状态下管理吗?

标签: javascript reactjs typescript ionic-framework axios


【解决方案1】:

在 React 方式中,1) 避免使用 querySelector 并获取值,以及 2) 在 render 方法中设置条件。像这样的一些怎么样。希望这会有所帮助。

this.state = {
    aletText: 0
}

componentDidMount() {
// change state (alertText or other delayedText) if required
}

handleAlerts() {
// change state (alertText or other delayedText) if required
}

render() {
    const { alertText } = this.state;
    // if required with delayedText, store in state and add condition here
    var alertClass = "number " + (alertText !== 0 ? "text-warning" : "text-success") ;
    return (<div id="alert" className={alertClass} onChange={this.handleAlerts}>{alertText}</div>)
}

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多