// 在app.js 中写一个
// 通过类组件修改状态的方式 counter
import React from "react"
class Counter extends React.Component {
render () {
return (<button>click</button>)
}
}
// 根组件
function App () {
return (
<div>
{/*渲染Hello组件 */}
<Counter></Counter>
</div >
)
}
export default App
这样就构建了一个项目初始化的样子
之后就定义状态,修改状态修改状态,完成counter需求
最终效果
// 通过类组件修改状态的方式 counter
import React from "react"
class Counter extends React.Component {
//1. 通过state定义组件状态
state = {
count: 0
}
// 2.给点击事件绑定一个回调函数
changeCount = () => {
// 1.修改state 不能直接修改
// 2 react这个体系下 `数据不可变` 就是不能通过 this.num++ num++ 改变数据 必须通过方法调用 satState
// value 永远是上一次count值+1
this.setState({
count: this.state.count + 1
})
}
render () {
return (<button onClick={this.changeCount}>{this.state.count}---click</button>)
}
}
// 根组件
function App () {
return (
<div>
{/*渲染Hello组件 */}
<Counter></Counter>
</div >
)
}
export default App
render : 是使用js的完全编程能力来渲染页面,即用js来构建DOM. render(){}