小记 React Element 类型
首先写 2 个组件,打印一下他们的属性:
const TextFunc = (props) => { console.log('render TextFunc',props) return <div>function</div> } class TextComponent extends React.Component { render() { console.log('render TextComponent', this.props) return <div>class qwerty</div> } }
打印结果:
$$typeof: Symbol(react.element) key: null props: {} ref: null type: { arguments: [Exception] caller: [Exception] length: 0 name: "TextFunc" __proto__: ƒ () } _owner: null _store: {validated: false} _self: null _source: null __proto__: Object
$$typeof: Symbol(react.element) key: null props: {} ref: null type: { class TextComponent arguments: [Exception] caller: [Exception] length: 0 name: "TextComponent" prototype: Component {constructor: ƒ, render: ƒ} __proto__: ƒ Component(props, context, updater) } _owner: null _store: {validated: false} _self: null _source: null __proto__: Object
略微比较一下,可以发现 只有 type 是不一样的, 他指向的是 class 和 function
大家都知道:
<TextFunc/>
其实是一个语法糖,他的真实语法是这样的:
React.createElement(TextFunc)
关于 children 的打印:
<TextFunc> <TextComponent/> </TextFunc>
children:{ $$typeof: Symbol(react.element) key: null props: {} ref: null type: class TextComponent _owner: null _store: {validated: true} _self: null _source: null __proto__: Object } // 或者是一个数组
children 传递的也是一个 createElement 的结果
想要修改 children,传递值给他 ,可以使用一个比较 hack 的方法:
const TextFunc = (props) => { console.log('render TextFunc', props) const {children} = props const element = React.createElement(children.type, { ...children.props, ...{ q: 123 } }) return <div> function <p>children:</p> { element } </div> }
比较正统的方法:
const TextFunc2 = (props) => { console.log('render TextFunc', props) const {children} = props const element = React.cloneElement(children, { ...children.props, ...{ q: 1234 } }) return <div> function2 <p>children2:</p> { element } </div> }
cloneElement 与 createElement 有点不一样, cloneElement接受的是一个元素,而createElement接受的是一个组件
React.cloneElement()
几乎等同于:
<element.type {...element.props} {...props}>{children}</element.type>
但是,这也保留了组件的ref
。这意味着当通过ref
获取子节点时,你将不会意外地从你祖先节点上窃取它。相同的ref
将添加到克隆后的新元素中。
不知道大家有没有分清组件
和元素
的区别了, 简单的说
组件被调用就成了元素
相关代码:
https://github.com/Grewer/JsDemo/blob/master/reactType/index.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧