点击事件(两种方式)
onClick={this.handleClick.bind(this)}
onClick={() => {this.handleClick()}}
State
this.setState 更改State中的值
constructor
这是ES6对类(Class)的默认方法,一般用于数据初始化,通过 new 命令生成对象实例时自动调用该方法。并且,该方法是类中必须有的,如果没有显示定义,则会默认添加。
super
继承它的父级
子类必须在constructor() 中调用 super() ,否则新建实例时会报错
State(状态)
组件内部的数据 可以动态改变
在 react 中,创建某一个响应式数据可以使用在 this.state = {} 中添加属性的方法,这一点和 Vue 有明显的不同,Vue 是在 data 属性中添加响应式数据;
class LikeBtn extends React.component { constructor(props) { super(props) this.state = { likes: 0 } } }
在 react 中,添加事件和事件监听函数:
例如:点击事件: onclick、事件监听函数: increaseLikes
使用驼峰命名原生 JS 事件onClick
并在 {} 中添加 this.increaseLikes
第一种写法:
increaseLikes() { // ... } render() { return ( <button onClick={this.increaseLikes}> like+ </button> ) }
第二种写法:
increaseLikes() { // ... } render() { return ( <button onClick={() => {this.increaseLikes()}}> like+ </button> { this.state.likes } ) }
上述两种写法,在 JSX 种使用箭头函数可以省略在组件 constructor 中在 this.increaseLikes 上绑定 this 的步骤;
如果不使用箭头函数,必须要在组件 constructor 中在 this.increaseLikes 上绑定 this,否则在事件监听函数中 this 为 undefined;
在事件监听函数中更改 state 里的数据时,需要使用 this.setState() 方法,传入对象,这里的对象就是 state 对象,用更改对象属性的方法更改 state 中的数据;
React基本结构
点赞的按钮
state
Component中所有方法调用this的时候,都不是自动绑定的,要通过代码进行bind
- this.increaseLikes = this.increaseLikes.bind(this)
- onClick = {() => { this.increaseLikes() }}
State属性是不能直接赋值更改的,改变它的唯一途径是this.setState({}),它的参数是一个object
使用setState 改变 state中的值
onClick调用方法需要手动绑定到当前类,默认this指向调用的组件;或者在调用onClick的时候使用箭头函数,不改变this指向,也可以
state
// this.increaseLikes = this.increaseLike.bind(this) //state的值不能够修改,因为其为纯函数,唯一改变state值的 方式就是调用setState({count:++this.state.count})方法
State值是不能直接修改的 唯一修改的途徑是調用setState方法
如果不用箭头函数,则需要绑定this。
onClick{ () => {this.increaseLikes() }}
绑定方法1:
onClick={this.increaseLikes.bind(this)
绑定方法2:
this.increaseLikes = this.increaseLikes.bind(this)
调用setState方法进行属性修改
使用bind函数将方法(this)绑定到对象上
JavaScript的类中的方法没有自动绑定this
stete是组件内部的数据状态,可以动态改变
flag,点赞按钮
属性:不可变,外部传入
状态(state):可变,私有
组件内部的数据可以动态改变
This.setState()是更新state的唯一途径
例:点赞按钮
state(状态)
组件内部的数据可以动态改变
this.setState()是更新state的唯一途径
constructor
需要显式调用super()
方法直接在类中定义,不需要像vue中定义在methods中
方法中的this默认指向是null,可以再构造其中进行绑定
也可以使用箭头函数(=>)
state改变
点赞按钮的详细代码
LikesButton代码
State 状态
组件私有的。