组件通信之子传父
子组件向父组件发送数据
下面我们先看一个例子:
import React,{Component} from "react";
import AddCounter from "./AddCount";
import SubCounter from "./SubCounter";
export class App extends Component{
constructor(){
super()
this.state = {
counter:100
}
}
changeCounter(count){
this.setState({counter:this.state.counter + count})
}
render(){
const { counter } = this.state
return (
<div>
<h2>当前计数:{counter}</h2>
<AddCounter addClick={(count)=>this.changeCounter(count)}></AddCounter>
<SubCounter subClick={(count)=>this.changeCounter(count)}></SubCounter>
</div>
)
}
}
export default App
上面代码中,实现了一个简易版的计数器,我们定义了两个子组件,分别用于增加和减少计数器,然后通过props将方法传递给子组件,子组件通过调用父组件传递过来的方法来改变父组件的状态。changeCounter
方法中,我们通过this.setState
来改变父组件的状态。
AddCounter组件(增加计数器)
我们先来看AddCounter组件,代码如下:
import React,{Component} from "react";
import PropTypes from "prop-types"
export class AddCounter extends Component{
addCount(count){
this.props.addClick(count)
}
render(){
return (
<div>
<button onClick={e => this.addCount(1)}>+1</button>
<button onClick={e => this.addCount(5)}>+5</button>
<button onClick={e => this.addCount(10)}>+10</button>
</div>
)
}
}
AddCounter.propTypes = {
addClick:PropTypes.func
}
export default AddCounter
这里我们注意,这个组件中的类型限定,我们通过PropTypes
来限定addClick
这个方法必须是一个函数PropTypes.func
。然后接着我们会通过this.props.addClick(count)
来调用父组件传递过来的方法来改变状态。this.props
是父组件传递过来的属性(这点和vue中的props类似)。然后我们在render
函数中通过this.addCount(1)
来调用我们定义的方法,该方法又会去调用父组件传递过来的方法。 这里为什么要用e => this.addCount(1)
箭头函数呢?因为箭头函数不会改变this的指向,如果不用箭头函数,那么this.addCount(1)
中的this
指向的是AddCounter
,而不是App
。
SubCounter组件(减少计数器)
我们再来看SubCounter组件,代码如下:
import React,{Component} from "react";
export class SubCounter extends Component{
subCount(count){
this.props.subClick(count)
}
render(){
return (
<div>
<button onClick={e => this.subCount(-1)}>-1</button>
<button onClick={e => this.subCount(-5)}>-5</button>
<button onClick={e => this.subCount(-10)}>-10</button>
</div>
)
}
}
export default SubCounter
这里我们也通过this.props.subClick(count)
来调用父组件传递过来的方法来改变状态。就不再过多赘述了。请看AddCounter组件
中的内容。
总结
通过上面的例子,我们可以看出,子组件向父组件发送数据的方法是通过props来传递的。然后父组件通过props来接收子组件传递过来的数据,然后通过props来调用父组件传递过来的方法来改变父组件的状态。这样就实现了子组件向父组件发送数据的目的。最后附上生成的效果图:
感谢大家观看,我们下次见
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我