import React from ‘react‘; class Baby extends React.Component { constructor (props) { super(props) this.state={ name:‘小兵‘ } //第二种改变this指向的方法 this.changeName2= this.changeName2.bind(this); } // 方法根render同级 方法1 changeName1(){ console.log(this.state.name) this.setState({ name:‘士兵‘ }) } // 方法根render同级 方法2 在构造函数中改变this指向(最常用的之一) changeName2(){ this.setState({ name:‘中师‘ }) } // 方法三 箭头函数绑定上下文的this就是组件本身(最常用就是这个) changeName3=()=>{ console.log(this) this.setState({ name:‘将军‘ }) } // 对于有参数的怎么搞函数有参数 getName=(e)=>{ this.setState({ name:e }) alert(e) } render (){ return ( <div> <p>我是{this.state.name}</p> <button onClick={this.changeName1.bind(this)}>点我改变名字方法@1</button> <button onClick={this.changeName2}>点我改变名字方法@2</button> <button onClick={this.changeName3}>点我改变名字方法@3</button> <br></br> <button onClick={this.getName.bind(this,‘我是传递的参数‘)}>函数有参数传递的写法</button> </div> ) } } export default Baby
React中好像没有简写 onClick Vue中有简写@click
React中事件的写法有三种最主要还是箭头函数这一种,vue 就@click=‘事件名‘,然后在methods中写对应的事件名(){ doSomething }有参数就传递参数就行了
React不一样啊,它没有vue的methos用于把所有方法集合到一起,它的方法跟render写在同级目录,而且写完之后不用加逗号,
其中React改变数据是
原文:https://www.cnblogs.com/myfirstboke/p/10479721.html