父组件 ===> 子组件 props
父组件:
render111(){
const cat = {
cat_name:'蓝猫',
cat_age:30
}
return <div>
<NoStateComponent name="张三丰" age={18}/><br/><br/><br/>
<StateComponent callback={this.getValue} cat={cat} name="金毛狮王" age={36}/>
</div>
}
有状态组件接受参数:
render(){
// console.log(this)
return <div>
我是有状态组件---{this.props.name}---{this.props.age}<br/>
我内部的数据---{this.state.nickname}<br/>
</div>
}
无状态组件接受参数:
import React from 'react'
// function NoStateComponent(props){
function NoStateComponent({name,age}){
// console.log("NoStateComponent---",props)
return <div>我是无状态组件---{name}---{age}</div>
}
// cjs esm
export default NoStateComponent
子组件 ===> 父组件 回调函数
子组件:
sendValueToParent = () => {
// console.log(this)
this.props.callback(this.state.nickname)
}
render(){
// console.log(this)
return <div>
<button onClick={this.sendValueToParent}>子组件传值给父组件</button>
</div>
}
父组件:
// 实例属性
getValue = (val) => {
console.log('---App---getValue---',val)
}
render111(){
const cat = {
cat_name:'蓝猫',
cat_age:30
}
return <div>
<StateComponent callback={this.getValue} cat={cat} name="金毛狮王" age={36}/>
</div>
}
兄弟组件传值
公共的bus
Vue 创建Vue的实例
React 靠events这个包【安装react就已经安装了】
1、创建公共的bus【EventEmitter】
bus.js:
import {EventEmitter} from 'events'
const bus = new EventEmitter()
// console.log(bus)
// 按需导出
export {bus}
2、在传递值的那一方,调用公共的bus.emit传值
bus.emit(事件名称,值):
import React, { Component } from 'react';
import {bus} from '../common/bus'
class Brother1 extends Component {
sendValueToBrother2 = () => {
// console.log("22222222")
bus.emit('myevent',{name:'小明',age:30})
}
render() {
return (
<div>
我是兄弟组件1<br/>
<button onClick={this.sendValueToBrother2}>传值给兄弟2</button>
</div>
);
}
}
export default Brother1
3、在接收值的那一方,调用公共的bus.on 接收值
bus.on(事件名称,处理函数):
import React from 'react'
import {bus} from '../common/bus'
export default class Brother2 extends React.Component{
constructor(){
super()
this.state = {
name:'',
age:0
}
bus.on('myevent',data => {
// console.log(data)
// this.setState({
// name:data.name,
// age:data.age
// })
this.setState(data)
})
}
render(){
return <div>
我是兄弟组件2 ---{this.state.name}---{this.state.age}
</div>
}
}
redux