Welcome to bingTang的博客! If you get any problems when reading, you can send me an email 1569025161@qq.com.
组件之间的通信方式
- 父向子
- 子向父
- 兄弟间
这里主要介绍前两种
1.父组件向子组件通信(子类用父类的资源)
子组件用父组件属性
eg:这里的
likedText
与unlikedText
123456789101112131415161718192021222324252627282930class LikeButton extends Component {render () {return (<ToggleButton likedText='喜欢' unlikedText='讨厌' />);}};class ToggleButton extends Component {constructor () {super();this.handleClickOnLikeButton = this.handleClickOnLikeButton.bind(this);this.state = {isLiked: true};}handleClickOnLikeButton () {this.setState({isLiked: !this.state.isLiked})}render () {return (<button onClick={this.handleClickOnLikeButton} >{this.state.isLiked ? this.props.likedText : this.props.unlikedText}</button>);}};
子组件用父组件方法
eg:这里的
handleChange
方法12345678910111213141516171819202122232425262728293031323334353637class HelloMessage extends Component {constructor () {super();this.handleChange = this.handleChange.bind(this);this.state = {value: 'Hello Runoob!'};}handleChange (event) {this.setState({value: '菜鸟教程'});}render () {return (<div><Content myDataProp = {this.state.value}that = {this}></Content></div>);}};class Content extends Component {handleClick () {let that = this.props.that;that.handleChange();}render () {console.log('updateStateProp',this.props.updateStateProp);return(<div><button onClick = {this.handleClick.bind(this)}>点我</button><h4 style={{fontSize: '20px'}}>{this.props.myDataProp}</h4></div>)}};- 这里将父类的
this
赋给that
属性 - 在子类中将父类的that属性赋给 that变量,
this.props.that
,再将父类的方法在子类中包装起来handleClick()
- 这样在子类中就可以直接调用
handleClick
啦!
- 这里将父类的
2.子组件向父组件通信(父类用子类的资源)
要调用子组件的方法或者属性,需要在调用子组件的时候定义ref
属性,且唯一
|
|
【总结】
1.子类调用父类方法时,
this.props.getSwordCount2()
,其中getSwordCount2
为父类的属性,调用它要加()
,12this.props.getSwordCount2; //这种写法不会调用的this.props.getSwordCount(); //这种写法会报错的2.父类调用子类方法时
通过
this.refs.getSwordButton
获取子类,然后.sendSword()
,其中sendSword()
为子类的方法3.回调的运用
想子类setSate之后再通过父类改变状态,
`this.setState({}, () => { 调用父类方法 });`
4.通知子类
父类改变状态之后,重新找到子类,给子类 setSate,