簡體   English   中英

如何基於document.body但在渲染之前設置狀態(反應)

[英]How to set state based on document.body but before render (react)

我有一個切換,我想根據 document.body.getAttribute("data-theme") 設置它的 defaultChecked。

如果主題很輕,則設置defaultChecked = "" ,如果不是defaultChecked = "true"

我已經意識到問題是當我想做這樣的事情時網站沒有完全加載:

this.state = {
  checked: document.body.getAttribute("data-theme") === "light" ? "" : "true",
};

這意味着我總是得到一些真實的東西。

這是完整的組件:

class Theme extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: document.body.getAttribute("data-theme") === "light" ? "" : "true",
    };
    this.handelChange = this.handelChange.bind(this);
  }

  componentDidMount() {
    let theme = localStorage.getItem("data-theme");
    document.body.setAttribute("data-theme", theme);
  }

  handelChange(evt) {
    if (evt.target.checked) {
      document.body.setAttribute("data-theme", "dark");
      localStorage.setItem("data-theme", "dark");
    } else {
      document.body.setAttribute("data-theme", "light");
      localStorage.setItem("data-theme", "light");
    }

    let lineColor = getComputedStyle(document.body).getPropertyValue("--sidebar-color");
    if (typeof InstallTrigger === "undefined") {
      lineColor = lineColor.substring(1);
    }
    this.props.colorChange(lineColor);
  };

  render() {
    return (
      <div onChange={this.handelChange} className="theme-switch-wrapper">
        <label className="theme-switch" htmlFor="checkbox">
          <input type="checkbox" id="checkbox" defaultChecked={this.state.checked} />
          <div className="slider round"></div>
        </label>
      </div>
    );
  }
}

export default Theme;

我認為你想要做的是:

class Theme extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: localStorage.getItem("data-theme") === "light" ? "" : "true"
    };
    this.handelChange = this.handelChange.bind(this);
  }

  componentDidMount() {
    let theme = localStorage.getItem("data-theme");
    this.setState({
      checked: theme === "light" ? "" : "true"
    });
  }

  handelChange(evt) {
    if (evt.target.checked) {
      localStorage.setItem("data-theme", "dark");
    } else {
      localStorage.setItem("data-theme", "light");
    }

    let lineColor = getComputedStyle(document.body).getPropertyValue(
      "--sidebar-color"
    );
    if (typeof InstallTrigger === "undefined") {
      lineColor = lineColor.substring(1);
    }
    this.props.colorChange(lineColor);
  }

  render() {
    return (
      <div onChange={this.handelChange} className="theme-switch-wrapper">
        <label className="theme-switch" htmlFor="checkbox">
          <input
            type="checkbox"
            id="checkbox"
            defaultChecked={this.state.checked}
          />
          <div className="slider round"></div>
        </label>
      </div>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM