关于react组件class中state的在构造函数中的位置读取顺序

问题描述

在学习react官方文档context时发现了一个问题,构造函数中声明了一个箭头函数和一个state,如果把state放在了箭头函数上面就没办法实现按钮换肤(按钮点击无反应,但不会报错)。放在后面就可以。
context-父子耦合-按钮换肤

相关代码

import...
//Context
import {ThemeContext, themes} from "./theme-context";
//按钮组件
import ThemeTogglerButton from './theme-toggler-btn';
class App extends React.Component {
    constructor(props) {
        super(props);
        //state放在这里就无法正常换肤
        /*this.state = {
            theme: themes.dark,
            toggleTheme: this.toggleTheme
        }*/
        this.toggleTheme = () => {
            this.setState(state => ({
                theme:
                    state.theme === themes.dark
                        ? themes.light
                        : themes.dark
            }))
        }
        //state放在这里就可以正常切换按钮的颜色
        this.state = {
            theme: themes.dark,
            toggleTheme: this.toggleTheme
        }
    }

    render() {
        return (
            <ThemeContext.Provider value={this.state}>
                <Content/>
            </ThemeContext.Provider>
        )
    }

}

function Content() {
    return (
        <div>
            <ThemeTogglerButton/>
        </div>
    )
}
ReactDOM.render(
    <App/>,
    document.getElementById('root')
)

其余的代码可以参考官方文档

这个问题估计没耐心或者没兴趣的大佬会懒得看,所以拜托一下也正在学习react的大佬们了

阅读 2.4k
1 个回答

你在箭头函数前后分别打印一下this吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题