父向子传值
Par (父组件)
import React from 'react';
class Parent extends React.Component{
state = {
num:0
}
render(){
return (
<div>
<Child num={this.state.num} />
</div>
)
}
}
Child (子组件)
class Child extends React.Compoent{
render(){
return {
<div>父组件传递过来的数据:{this.state.num}</div>
}
}
}
子向父传值
Child (子组件)
class Child extends React.Component{
state = {
ChildData:"子组件的数据"
}
send = ()=>{
this.state.getChildVal(this.state.ChildData)
}
render(){
return(
<div>这是子组件</div>
<button onClick={this.send}>发送</button>
)
}
}
Parent(父组件)
import React from "react";
class Parent extends React.Component{
state = {
msg:""
}
getData = params =>{
// 父组件传递过来的数据
console.log(params)
this.setState({
msg:params
})
}
render(){
return(
<div>这是父组件</div>
<Child getChildVal={this.getData}/>
)
}
}
兄弟之间传值
Parent 父组件
import React from "react";
class Parent extends React.Component{
state = {
count:""
}
getvalue = () => {
this.setstate({
count : this.state.count + 1
})
}
render(){
return (
<div>
<Child1 num={this.state.count}/>
<Child2 getval={this.getvalue}/>
</div>
)
}
}
Child1(兄弟1)
class Child1 extends React.Component{
render(){
return (
<div>
兄弟一:{this.props.num}
</div>
)
}
}
Child2(兄弟2)
class Child2 extends React.Component{
render(){
return (
<div>
兄弟二:
<button onClick = {()=>{this.state..getval()}} >+1</button>
</div>
)
}
}