React随想录–第三树
-
状态属性state的修改只能是通过 this.setstate内置方法修改 方法内部有两个参数
-
第一个参数为对象 修改是以对象的形式修改
-
[ ]
this.state = { froag:true } this.setState({ froag:false })
-
-
第一个参数为函数 (一般是对象属性的值为数组的时候)//注意函数必须要有返回值
-
[ ]
this.state = { list:[ {id:1,title:'娃哈哈'}, {id:2,title:'旺仔牛奶'} ] } this.setState(()=>{ this.state.list.push({id:this.state.list.length+1,title:'haha'}) return{list:this.state.list}
-
-
-
事件的四种形式 注意: 事件不能定义在函数式组件中 在需要传参数的时候需要在标签内在套用一层箭头函数
- 内部嵌套
<button onClick = {()=>{alert(1)}}>{info}</button>//不推荐
-
在组件内使用箭头函数定义一个方法(推荐)*
addlist = () => { //这里用箭头函数的原因是为了让函数内部的this指向组件实例 this.setState(()=>{ this.state.list.push({id:this.state.list.length+1,title:'haha'}) return{list:this.state.list} } ) } <button onClick = {this.addlist}>添加</button>
-
直接在组件内定义一个非箭头函数的方法
<button onClick={this.handleClick.bind(this)}></button>//改变this的指向
-
直接在组件内定义一个非箭头函数的方法,然后在constructor里bind(this)
this.handleclick = this.handleclick.bind(this)//在构造函数里面声明 <button onClick={this.handleClick}></button>
-
组件通信
-
父子组件通信
-
属性传值的方式
<Son tick = {this.tick}></Son>//子组件传参 tick = () =>{ this.Sister.changefloag()//父组件值 } <button onClick = {this.props.tick}>锤他</button>//通过props获取父组件的值
-
-
子父组件通信
- 数据的修改只能在自己的组件内修改 子父通信的本质方法的传递
export default class Son extends Component{ constructor(props){ super(props) this.state = { money:10000 } console.log(this.props) } render(){ const {money} = this.state return ( <button onClick = {()=>{ this.props.changemoney(money)//子组件传参(子组件的数据) }}>发红包</button> ) } }子组件 export default class Father extends Component{ constructor(){ super() this.state = { money:0 } } changemoney = (value) => {//value通过子组件传过来 this.setState({ money:value }) } render(){ const {money} = this.state return ( <Fragment> <p>儿子给了我{money}</p> <Son changemoney = {this.changemoney}></Son> </Fragment> ) } }//父组件
-
跨组件通信
-
非父组件 通过ref 获取 子组件的东西绑定到父组件中 然后通过父传递给子组件
import React, {Component,Fragment} from 'react' class Son extends Component { constructor(props){ super(props) } render(){ return( <button onClick = {this.props.tick}>锤他</button> ) } } class Sister extends Component { constructor(props){ super(props) this.state = { froag:true } } changefloag = ()=>{ this.setState({ froag:false }) } render(){ const {froag} = this.state return( <Fragment> <p>{froag && "笑" || "哭"}</p> </Fragment> ) } } export default class Father extends Component{ constructor(props){ super(props) } tick = () =>{ this.Sister.changefloag() } render(){ return( <div> <Son tick = {this.tick}></Son> <Sister ref = {el => this.Sister = el}></Sister> </div> ) } }
-