使用 this.setState 修改 state 上的数据|学习笔记

简介: 快速学习使用 this.setState 修改 state 上的数据

开发者学堂课程【React 入门与实战:使用 this.setState 修改 state 上的数据】学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址:https://developer.aliyun.com/learning/course/585/detail/8117


使用 this.setState 修改 state 上的数据

export default class BindEvent extends React.Componen{constructor(){

super()

//私有数据

this.state = {}

}

render(){

return <div>

BindEvent 组件

<hr/>

{/*在 React 中,有一套自己的事件绑定机制:事件名,是小驼峰命名"/}

{/* <button onClick={function(){ console.log('ok') }}>按钮</button> */}

{/* <button onClick={this .myclickHandler}>按钮</button> */}

{/*注意: onClick 只接受 function 作为处理函数*/}

<button onClick={ ()=>{ this .myclickHandler() } }>按钮

</button>

在 React 中,如果想要修改 state 中的数据,推荐使用

this.setState({ })

如下:

export default class BindEvent extends React.Component{

construcntor(){
super()
this.state = {

msg:’哈哈’

}
}

render(){
return <div>

{/*需求:点击按钮,把修改 msg 的值*/}
<button onClick={ () => this. show('
图片’,’图片’)}>按钮</outton>

image.png

<h3>{this.state.msg}</h3>
//    </div>
//   }

show =(arg1,arg2) => {

// console.log(‘show方法被调用了’+ arg1 + arg2)

//注意: React 中,如果想为 state 中的数据,重新赋值,不要使用 this.state.***=值

//应该调用 React 提供的 this.setState({ msg:’123’})

image.png

//This.stste.msg=’oooooo’

//在 React 中,推荐使用 this.setState({})修改 状态值

This.setState({

Msg:’123’+ arg1 + arg2

})

}
}

用的最多的事件绑定形式为:

<button onClick-{()=>this.show('传参') }>按钮</button>

//事件的处理函数,需要定义为一个箭头函数,然后赋值给函数名称show = (arg1) =>{
console.log('show
方法'+arg1)
}
在 React 中,如果想要修改 state 中的数据,推荐使用 thil.setState({ })

相关文章
【Emit基础】在IL中进行异常处理
本文通过一个简单的示例来说明在IL中进行异常处理时要注意的关键点。      我们来看一个包含try...catch...finally的示例:         public void TestEF()         {                       Transa...
944 0
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8083 2
|
12天前
|
域名解析 人工智能 Linux
|
20天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10368 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
6天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1567 5
|
9天前
|
云安全 数据采集 人工智能