State传统方式
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>React Demo</title> <!-- 引入React --> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <!-- 引入ReactDOM --> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <!-- 引入Babel用于转换JSX(如果你不是通过构建工具如Webpack来转换的话) --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body><div id="test"></div> <script type="text/babel">class Weather extends React.Component{constructor(props) {super(props)// 初始化状态this.state={isHot:false}this.changeWrather = this.changeWrather.bind(this)}render() {// 读取状态const {isHot} = this.statereturn <h1 onClick={this.changeWrather}>今天天气很{isHot?'炎热':'凉爽'}</h1>}changeWrather() {// 获取原来的isHotconst isHot = this.state.isHot// 注意:状态必须通过setState进行更新 状态state不可直接更改this.setState({isHot:!isHot})}}// 渲染ReactDOM.render(<Weather/>,document.getElementById('test'))</script>
</body>
</html>
State简写方式(推荐)
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>React Demo</title> <!-- 引入React --> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <!-- 引入ReactDOM --> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <!-- 引入Babel用于转换JSX(如果你不是通过构建工具如Webpack来转换的话) --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body><div id="test"></div> <script type="text/babel">//创建组件class Weather extends React.Component{// 初始化状态state={isHot:false}render() {// 读取状态const {isHot} = this.statereturn <h1 onClick={this.changeWrather}>今天天气很{isHot?'炎热':'凉爽'}</h1>}// 自定义方法changeWrather=() =>{// 获取原来的isHotconst isHot = this.state.isHot// 注意:状态必须通过setState进行更新 状态state不可直接更改this.setState({isHot:!isHot})}}// 渲染ReactDOM.render(<Weather/>,document.getElementById('test'))
</script>
</body>
</html>