react 入门

  • react 入门已关闭评论
  • 94 次浏览
  • A+
所属分类:Web前端
摘要

react三大属性一.状态类组件
1. state 是组件的属性,值是对象。state中的数据是可读可写的,通过更新state来更新对应的页面显示(重新渲染组件),通过setState来更新state数据且更新是一种合并 ,在类组件中使用.
组件自定义的方法中this为undefined
(1)强制绑定this: 通过函数对象的bind()
(2)箭头函数

react三大属性

一.状态

类组件
1. state 是组件的属性,值是对象。state中的数据是可读可写的,通过更新state来更新对应的页面显示(重新渲染组件),通过setState来更新state数据且更新是一种合并 ,在类组件中使用.
组件自定义的方法中this为undefined
(1)强制绑定this: 通过函数对象的bind()
(2)箭头函数

class Demo extends Component {   //定义   state = {date: new Date(),count:0};   //为addClick强制绑定this   addClick=this.addClick.bind(this);    //addClick在未强制绑定this的时候无法在addClick内访问this.state   //this指向是undefined   addClick(){
   const {count} =this.state //修改state中count的值,当点击的时候加1 this.setState({count:count+1}) } //箭头函数 minusClick=()=>{
   const {count} =this.state this.setState({count:count-1}) } render() { const {date,count}=this.state return ( <div> <h1>计数{count}</h1> <h2>时间 {date.getDate()}.</h2> <button onClick={this.addClick}>加</button> <button onClick={this.minusClick}>减</button> </div> ); } }

 

函数组件

1. useState 在函数组件里用 返回一个数组:状态和一个修改状态的方法, 状态需要通过这个方法来进行修改并触发视图更新'渲染页面'

   const [count,setCount]=useState(0)      const addClick=(()=>{         setCount(count+1)     })     const minusClick=(()=>{         setCount(count-1)     })              return (         <div>             <header>             <h3>计数:{count}</h3>             <button onClick={addClick}>加</button>             <button onClick={minusClick}>减</button>             </header>         </div>     );