一、state是什么
从字面上来书state就是状态,在React中,state驱动页面的展示,它负责存放数据。
二、state的使用
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>初始化state</title> <script src="https://unpkg.com/react@18/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <!-- Don't use this in production: --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <!-- 准备一个容器 --> <div id="test"></div> </body> <script type="text/babel"> //定义类组件 class MyComponent extends React.Component { //构造器,且传入props参数,固定写法 constructor(props) { super(props) //状态,它的位置是在实例对象的上面 this.state = { isDog: true } } render() { console.log(this) //对象解构(ES6语法) const { isDog } = this.state return ( <div> <h1> <span>这是一只{isDog ? '狗' : '猫'}</span> </h1> </div> ) } } //react渲染 ReactDOM.render(<MyComponent />, document.getElementById("test")) </script> </html>
标签:初始化,render,React,state,isDog,props From: https://www.cnblogs.com/jmsstudy/p/17591387.html