无法在回调函数中获取当前状态值

问题描述 投票:0回答:1

在第一次运行中,

theme = 'dark'
。然后,单击跨度后,主题状态就会发生变化。但我无法在回调函数中获取更新的状态。有人可以帮忙吗?

This my state for theme

This my callback function

reactjs state
1个回答
0
投票

单击嵌套的

onClick()
时,div 上的
span
不会检测到任何更改。

您需要将

onClick
添加到每个
span
,但这需要将参数传递给
handleTheme
函数。

由于跨度内没有任何文本,我们可以使用

className
来设置主题变量。 (更好的是使用例如
data-theme
)。

这样就可以使用了

e.target.classList.toString()

在您的示例中获取按下的主题。


const { useState } = React;

const Example = () => {

    const [theme, setTheme] = useState("dark");

    const handleTheme = (e) => {
        const themeFromClass = e.target.classList.toString();
        setTheme(themeFromClass);
    }
    
    return (
        <div>
            <h1>{`Current theme: ${theme}`}</h1>
            <div className="themeSelector">
                <span onClick={handleTheme} className="light">Light</span><br />
                <span onClick={handleTheme} className="dark">Dark</span>
            </div>
        </div>
    )
}
ReactDOM.render(<Example />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

© www.soinside.com 2019 - 2024. All rights reserved.