react组件传值
1. 父子传值
父传子使用props,父组件更新视图改变props子组件会同步更新。
类组件
import React, { Component } from 'react'; class Father extends Component { state={ count: 0 } render(){ return ( <Child count={count} /> ) } } class Child extends Component { constructor(){ super(props); // 必须先用super方法传入props,才能在constructor中使用this.props console.log(this.props); // 0 } return ( <div>{this.props.count}</div> // 0 ) }
函数组件
import { useState, useEffect } from 'react'; function Father(){ const [ count, setCount ] = useState(0); return ( <Child count={count} /> ) } // 需要传入props参数 function Child(props){ console.log(props.count); // 0 useEffect(()=>{ console.log(props.count); // 0 },[]) return ( <div>{props.count}</div> // 0 ) }
子传父使用回调函数以参数的形式返回给父组件
类组件
import React,{Component} from 'react'; import {Button} from 'antd'; class Father extends Component{ result(params){ console.log(params); // 'aaa' } render(){ return ( <div> <div>父组件</div> <Child back={(params)=>{this.result(params)}} /> </div> ) } } class Child extends Component{ render(){ return ( <Button type="primary" onClick={()=>{this.props.back('aaa')}}>我是子组件,点击我将子组件数据传到父组件</Button> ) } }
函数组件
import {Button} from 'antd'; function Father(){ const result = (params)=>{ console.log(params); // 'aaa' } return ( <div> <div>父组件</div> <Child back={(params)=>{ result(params) }}/> </div> ) } // 记得传入props参数 function Child(props){ return ( <Button type="primary" onClick={()=>{props.back('aaa')}}>我是子组件,点击我将子组件数据传到父组件</Button> ) }
父组件调用子组件的方法
类组件
import React,{Component} from 'react';
import { Button } from 'antd'; class Father extends Component{ handle(){ this.Child.func() } render(){ return ( <div> <Button type="primary" onClick={()=>{this.handle()}}>我是父组件,点击我获取子组件方法</Button> <Child onRef={node=>{this.Child = node}} /> </div> ) } } class Child extends Component{ componentDidMount(){ this.props.onRef && this.props.onRef(this); } func(){ console.log('我是子组件方法!') } render(){ return ( <div>我是子组件</div> ) } }
函数组件
import { useImperativeHandle } from 'react'; import { Button } from 'antd'; function Father() { const handle = () => { ChildRef.current.func(); } let ChildRef = React.createRef(); return ( <div> <div> <Button type="primary" onClick={handle}>我是父组件,点击我调用子组件方法</Button> </div> <Child onRef={ChildRef} /> </div> ) } function Child(props) { // 用useImperativeHandle暴露外部ref能访问的属性和方法 useImperativeHandle(props.onRef, () => { return { func: func } }) const func = () => { console.log('我是子组件方法') } return ( <div>子组件</div> ) }
2. 非父子传值
非父子组件间传值可以使用以下方法:
- 共同父组件当中间人方式
- 发布订阅
- useContext
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~