父子组件传值
import React from "react"
/*父组件*/
class Father extends React.Component{
constructor(props) {
super(props)
this.state = {
count:0
}
}
handleAdd = ()=>{
this.setState({
count:this.state.count + 1
})
}
render(){
return(
<div>
父子传值
<button onClick={this.handleAdd}>加一</button>
<Child count={this.state.count}/>
</div>
)
}
}
/*子组件*/
const Child = (props)=>{
return(
<div>子组件接收 {props.count}</div>
)
}
子父组件传值
import React from "react"
/*父组件*/
class Father extends React.Component{
constructor(){
super()
this.state = {
getChildCount:0
}
}
getCount = (data)=>{
this.setState({
getChildCount:data
})
}
render(){
return(
<div>
子组件传参 {this.state.getChildcount}
<Child getCount={this.getCount}/>
</div>
)
}
}
/*子组件*/
class Child extends React.Component{
constructor(props){
super(props)
this.state = {
count:0
}
}
handelAdd = ()=>{
this.setState((state)=>{
let newValue = state.count + 1
this.props.getCount(newValue)
return{
count:newValue
}
})
}
render(){
return(
<div>
子组件
<button onClick={this.handelAdd}>加一</button>
</div>
)
}
}
兄弟组件传
兄弟组件传值,完成思路在于把所有的状态放在父组件上,两个兄弟组件通过父子、子父传值的方法,实现兄弟组件之间的通信。
import React from "react"
class Father extends React.Component {
constructor(props){
super(propss)
this.state = {
count:0
}
}
getCount = (data)=>{
this.setState((state)=>{
return{
count:state.count + data
}
})
}
render(){
return{
<div>
兄弟组件传值
<Child count={this.state.count}/>
<Child2 getCount={this.getCount}/>
</div>
}
}
}
class Child extends React.Component {
constructor(props){
super(props)
}
render(){
return{
<div>
<div>子组件一</div>
<div>计数器:{this.props.count}</div>
</div>
}
}
}
class Child2 extends React.Component {
constructor(props){
super(props)
}
handelAdd = ()=>{
this.props.getCount(1)
}
render(){
return{
<div>
<div>子组件二</div>
<button onClick={this.handelAdd}>加一</button>
</div>
}
}
}