为什么我的 onClick 在组件渲染时被触发?

时间:2021-05-15 15:39:12

标签: reactjs

在下面的代码(完整代码的摘录)中,ContextHookInfo组件的按钮onClick在我刷新页面时直接被触发,我不知道为什么。请问有人有想法吗?

const UseContextTheme = {
    light: {
        name: 'light',
        style: {
            color: "#0f0",
            backgroundColor: "#fff"
        }
    },
    dark: {
        name: 'dark',
        style: {
            color: "#fff",
            backgroundColor: "#0f0"
        }
    }
}

const HookContext = React.createContext({ selectedTheme: UseContextTheme.light, themeSetter: () => {} });

function App() {
    const [useContextSelectedTheme, useContextThemeSetter] = useState(UseContextTheme.dark);
    return (
        <HookContext.Provider value={{ selectedTheme: useContextSelectedTheme, themeSetter: useContextThemeSetter}}>
            <ContextHookTest>
                <ContextHookInfo />
            </ContextHookTest>
        </HookContext.Provider>
    );
}

function ContextHookInfo() {
    const themeContext = React.useContext(HookContext);
    console.log("Theme:", themeContext);
    return (
        <div>
            <p style={themeContext.selectedTheme.style}>Hook theme color is {themeContext.selectedTheme.name}</p>
            <button onClick={themeContext.themeSetter()}>Change hook theme</button>
        </div>
    );
}

1 个答案:

答案 0 :(得分:1)

将函数 onClick={themeContext.themeSetter()} 更改为 onClick={themeContext.themeSetter}