如何在React中选择HTML元素?

huangapple go评论64阅读模式
英文:

How to select the html element in React?

问题

我想选择主题值以根据localStorage值更改它来设置明亮/暗主题,我该如何在React中实现这个目标?

我知道我可以在组件中使用Ref钩子,但我该如何选择index.html中的DOM元素?

英文:

I want to select the theme value to change it based on localStorage value to set the light/dark theme, how can I do that in React?

如何在React中选择HTML元素?

I know I can use Ref hook in a component but how can I select a dom element in index.html?

答案1

得分: 0

你可以只使用纯JS选择HTML元素:

document.getElementsByTagName("html")[0].setAttribute("theme", "dark")

这会获取所有带有标签"html"的元素列表,选择第一个元素,然后设置"theme"属性。然后,您可以读取localStorage并相应地设置主题值。

查看setAttribute的文档。

英文:

You can just select the html element using vanilla js:

document.getElementsByTagName("html")[0].setAttribute("theme","dark")

This gets a list of all elements with the tag "html", selects the first one, and then sets the "theme" attribute. You can then use read the localStorage and set the theme value accordingly.

See the documentation for setAttribute

答案2

得分: 0

你已经提供了一个具有theme属性设置为"dark"的HTML标签。但是,theme属性不是标准的HTML属性,因此默认情况下不会对页面的外观产生任何影响。请使用data-theme作为属性。
创建一个带有默认主题值的状态。创建一个切换函数,并在按钮的onClick事件中调用此函数。

const toggleTheme = () => {
  const newTheme = theme === 'light' ? 'dark' : 'light';
  setTheme(newTheme);
  localStorage.setItem('theme', newTheme); // 将新的主题偏好保存到localStorage
  document.documentElement.setAttribute('data-theme', newTheme); // 将选定的主题类应用于html元素
};
英文:

You have provided an HTML tag with a theme attribute set to "dark." However, the theme attribute is not a standard HTML attribute, so it won't have any effect on the page's appearance by default. Use data-theme as attribute.
Create a state with a default theme value. Create a toggle function and call this function onClick of a button.

 const toggleTheme = () => {
const newTheme = theme === 'light' ? 'dark' : 'light';
setTheme(newTheme);
localStorage.setItem('theme', newTheme); // Save the new theme preference to localStorage
document.documentElement.setAttribute('data-theme', newTheme); // Apply the selected theme class to the html element

};

答案3

得分: 0

<html theme="dark">更改为<html class="dark">,然后添加单独的.light.dark CSS类。然后,您可以创建一个自定义钩子,将其导入到具有切换功能的组件中。

在这里,自定义钩子(useToggleTheme)初始化一个状态并返回一个函数。该函数根据当前状态声明一个新的主题,更改文档元素(<html>)上的类,然后使用该值设置新状态。这个函数就是您的按钮调用的函数。

const { useState } = React;

function useToggleTheme() {
  const [theme, setTheme] = useState('dark');

  function toggleTheme() {
    const newTheme = theme === 'dark' ? 'light' : 'dark';
    document.documentElement.className = newTheme;
    setTheme(newTheme);
  }

  return toggleTheme;
}

function Example() {
  const toggleTheme = useToggleTheme();

  return (
    <div>
      <button onClick={toggleTheme}>
        切换主题
      </button>
    </div>
  );
}

const node = document.getElementById('root');
const root = ReactDOM.createRoot(node);
root.render(<Example />);
.dark { background-color: darkgray; color: white; }
.light { background-color: white; color: darkgray; }
<html class="dark">
<body>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
</body>
</html>
英文:

Change &lt;html theme=&quot;dark&quot;&gt; to &lt;html class=&quot;dark&quot;&gt;, and then add separate .light and .dark CSS classes. You can then create a custom hook that you can import into the component that has the toggle functionality.

Here the custom hook (useToggleTheme) initialises a state and returns a function. The function declares a new theme depending on the current state, changes the class on the document element (&lt;html&gt;), and then sets the new state with that value. This function is what your button calls.

<!-- begin snippet: js hide: false console: true babel: true -->

<!-- language: lang-js -->

const { useState } = React;

function useToggleTheme() {

  const [theme, setTheme] = useState(&#39;dark&#39;);

  function toggleTheme() {
    const newTheme = theme === &#39;dark&#39; ? &#39;light&#39; : &#39;dark&#39;;
    document.documentElement.className = newTheme;
    setTheme(newTheme);
  }

  return toggleTheme;

}

function Example() {

  const toggleTheme = useToggleTheme();

  return (
    &lt;div&gt;
      &lt;button onClick={toggleTheme}&gt;
        Toggle theme
      &lt;/button&gt;
    &lt;/div&gt;
  );

}

const node = document.getElementById(&#39;root&#39;);
const root = ReactDOM.createRoot(node);
root.render(&lt;Example /&gt;);

<!-- language: lang-css -->

.dark { background-color: darkgray; color: white; }
.light { background-color: white; color: darkgray; }

<!-- language: lang-html -->

&lt;html class=&quot;dark&quot;&gt;
&lt;body&gt;
&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年8月4日 05:53:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定