react setState的使用

geekymv 发表于:2024-08-15 22:47:45 阅读数:369

react setState的使用

<div id="test"></div>

        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

        <!-- 引入 babel, 用于将 jsx 转为 js -->
        <!-- Don't use this in production: -->
        <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

        <!-- 此处一定要写 babel -->
        <script type="text/babel">
            class Weather extends React.Component {

                constructor(props) {
                    super(props)
                    // 初始化状态
                    this.state = {isHot: false}
                    // 解决 changeWeather 中的 this 指向问题
                    this.changeWeather = this.changeWeather.bind(this)
                }

                render() {
                    // return <h2>今天天气{this.state.isHot ? '很热' : '很冷'}</h2>
                    // return <h2 onClick={demo()}>今天天气{this.state.isHot ? '很热' : '很冷'}</h2>
                    return <h2 onClick={this.changeWeather}>今天天气{this.state.isHot ? '很热' : '很冷'}</h2>
                }

                /*
                changeWeather 是作为 onClick 的回调,所以不是通过实例调用的,是直接调用
                */
                changeWeather() {
                    // 类中的方法默认开启了局部严格模式,所以 changeWeather 中的 this 为 undefined
                    const isHot = this.state.isHot
                    // 状态必须通过 setState 进行更新,且更新是一种合并,不是替换
                    this.setState({isHot: !isHot})

                }
            }

            ReactDOM.render(<Weather/>, document.getElementById('test'))

        </script>



Barbara Middleton
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis porta eros lacus, nec ultricies elit blandit non. Suspendisse pellentesque mauris sit amet dolor blandit rutrum. Nunc in tempus turpis.
Like · Reply · 3 hrs

Sean Brown
Donec sollicitudin urna eget eros malesuada sagittis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam blandit nisl a nulla sagittis, a lobortis leo feugiat.
Like · Reply · 2 hrs

Vivamus quis semper metus, non tincidunt dolor. Vivamus in mi eu lorem cursus ullamcorper sit amet nec massa.
Morbi vitae diam et purus tincidunt porttitor vel vitae augue. Praesent malesuada metus sed pharetra euismod. Cras tellus odio, tincidunt iaculis diam non, porta aliquet tortor.

Kayli Eunice
Sed convallis scelerisque mauris, non pulvinar nunc mattis vel. Maecenas varius felis sit amet magna vestibulum euismod malesuada cursus libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus lacinia non nisl id feugiat.
Like · Reply · 2 hrs