1.父传子和子传父(类似vue):在子组件标签中用自定义属性进行传递,接收的时候通过 this.props 进行接收;在子组件标签内部用自定义属性定义一个方法传递给子组件 子组件调用这个方法【这个方法可以再this.props中访问到】传递参数
子组件
import React, {Component} from 'react'
export default class News extends Component {
constructor(props){
super(props)
this.state={
num:123
ziText:"我是默认值"
}
},
fun(){
this.setState({
num:321
})
},
render(){
return (
<div>
/* 子组件this.props.text(自定义属性)接收 */
News_____{this.props.text}___{this.state.num}
<button onClick={this.fun.bind(this)}>点我</button>
/* 子组件this.props.fufun.bind(this,this.state.ziText)(自定义方法fufun)触发 */
<button onClick={this.props.fufun.bind(this,this.state.ziText)}>点我进行数据的发送</button>
</div>
)
}
}
父组件
import React, {Component} from 'react'
import News from "./News"
export default class Home extends Component {
constructor(props){
super(props)
this.state={
text:"我是默认值"
}
},
dataFun=(text)=>{
/* 形参名称与参数名称相同,es6写法 */
this.setState({
text
})
},
render(){
return (
<div>
home _____{this.state.text}
/* 父组件【自定义属性为 text 传的值为 你好】;在父组件中通过调用自组件中自定义的fufun方法接收传递过来的值 */
<News text="你好" fufun={this.dataFun}/>
</div>
)
}
}
2.同级组件间传值: 使用pubsub插件
指令:npm install --save pubsub-js
父组件
import React, {Component} from 'react'
import News from "./News"
import Phone from "./Phone"
export default class Home extends Component {
constructor(props){
super(props)
this.state={
text:"我是默认值"
}
},
dataFun=(text)=>{
/* 形参名称与参数名称相同,es6写法 */
this.setState({
text
})
},
render(){
return (
<div>
home _____{this.state.text}
<News text="你好" fufun={this.dataFun}/>
<Phone />
</div>
)
}
}
子组件1 News
import React, {Component} from 'react'
import Pubsub from 'pubsub-js'
export default class News extends Component {
constructor(props){
super(props)
this.state={
num:123
ziText:"我是默认值"
}
},
fun(){
this.setState({
num:321
})
},
pubsub(){
/* 通过 PubSub.publish方法传值*/
PubSub.publish('evt',this.state.num)
}
render(){
return (
<div>
/* 子组件this.props.text(自定义属性)接收 */
News_____{this.props.text}___{this.state.num}
<button onClick={this.fun.bind(this)}>点我</button>
/* 子组件this.props.fufun.bind(this,this.state.ziText)(自定义方法fufun)触发 */
<button onClick={this.props.fufun.bind(this,this.state.ziText)}>点我进行数据的发送</button>
/* 通过 pubsub 方法传值*/
<button onClick={this.pubsub.bind(this)}>点我进行同级传值</button>
</div>
)
}
}
子组件2 Phone
import React, {Component} from 'react'
import Pubsub from 'pubsub-js'
export default class Phone extends Component {
constructor(props){
super(props)
/* PubSub.subscribe 接收 */
PubSub.subscribe("evt",(msg,data)=>{
console.log(data)
})
},
render(){
return (
<div>
phone
</div>
)
}
}