React 组件通信

发布于:2025-06-22 ⋅ 阅读:(17) ⋅ 点赞:(0)

在这里插入图片描述

父传子

函数式组件

function Footer(props){
    const [count,setCount] = useState(0)
    const {name,age} = props

    const onClick = ()=>{
        setCount(count+1)
    }

    return (<div>
        <button onClick={()=>{onClick()}}>点此+1</button>
        <div>{count}</div>
        <div>name是:{name}年龄是:{age}</div>

    </div>)
}

类组件

class Header extends React.Component{
    constructor(props){
        super()
        this.props = props

    }

    render(){
        const {name,age} = this.props
        return (<div>
        <div>name是:{name}年龄是:{age}</div> 
        </div>)
    }
}

也可以直接在constructor中super(props)

constructor(props){
        super(props)


    }

通信时的属性验证

进行一个typescript的使用

父传子 通过回调函数

类组件中

class CounterButton extends React.Component{
    constructor(props){
        super(props)
    }
    render(){
        const {handlecallback} = this.props
        return (<button onClick={handlecallback}>接口anniu组件</button>)
    }
}

如图,通过props中父组件传递过来的increase函数实现增加

父组件传值

<CounterButton handlecallback={this.increase}/>

函数式组件中

function DeButton(props){
    const {handlecallback} = props

    return (<button onClick={handlecallback}>函数式子减小button</button>)
}

父组件传值

 <DeButton handlecallback={this.decrease}></DeButton>

父传更远的子代的传递 Context

在这里插入图片描述
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到