是否可以在不渲染的情况下深度遍历 React 子项
Is it possible to deep traverse React Children without rendering?
有没有办法抓取"静态"<Wrapper/>
中的所有bar
属性,例如不渲染?
import React from 'react';
import ReactDOM from 'react-dom';
class Foo extends React.Component {
render() {
return(
<div>
<span bar="1" /> // want to collect this 'bar'
<span bar="2" /> // want to collect this 'bar'
</div>;
);
}
}
class FooTuple extends React.Component {
render() {
return(
<div>
<Foo />
<Foo />
</div>;
);
}
}
class Wrapper extends React.Component {
render() {
React.Children.forEach(this.props.children, child => {
console.log(child.props); // can only see <FooTuple/> not <Foo/>
});
return(
<div>
{this.props.children}
</div>;
);
}
}
ReactDOM.render(
<Wrapper>
<FooTuple />
</Wrapper>,
document.getElementById('app'));
这是一个天真的尝试的 webpackbin,试图迭代显然不起作用child.children
,但如果它有帮助,它就在这里:http://www.webpackbin.com/EySeQ-ihg
TL;DR;不,这是不可能的。
--
我曾经遇到过同样的问题,试图遍历一棵嵌套深度的子树。以下是我的独家新闻:
所需知识
-
children
是放置在jsx
打开和关闭标签内的内容,或直接注入儿童道具中的东西undefined
children
。<div className="wrapper"> // Children <img src="url" /> </div> /* OR */ <div classname="wrapper" children={<img src="url" />}>
-
children
是一个不透明的树状数据结构,表示 react 元素的树,但它很可能是jsx
在转译时实现的React.createElement
输出。{ $$typeof: Symbol(react.element), type: 'div', key: null, ref: null, props: { className: "wrapper", children: { $$typeof: Symbol(react.element), type: 'img', key: null, ref: null, props: { src: 'url' }, } } }
-
创建
React
元素并不意味着它们被实例化,将它们视为React
用来呈现这些元素的描述符。 换句话说,实例由幕后React
本身来处理。
穿越子项
让我们以您的示例为例,尝试遍历整棵树。
<Wrapper>
<FooTuple />
</Wrapper>
这些元素的不透明子对象将是这样的:
{
$$typeof: Symbol(react.element),
type: Wrapper,
key: null,
ref: null,
props: {
children: {
$$typeof: Symbol(react.element),
type: FooTuple,
key: null,
ref: null,
props: {},
}
}
}
如您所见FooTuple
道具是空的,原因您现在应该知道。访问其子元素的唯一方法是使用它的type
实例化元素,以便能够调用其 render 方法来获取其底层子元素,如下所示:
class Wrapper extends React.Component {
render() {
React.Children.forEach(this.props.children, child => {
const nestedChildren = new child.type(child.props).render();
console.log(nestedChildren); // `FooTuple` children
});
return(
<div>
{this.props.children}
</div>;
);
}
}
这显然根本不是需要考虑的事情。
结论
没有干净的方法来增加深度嵌套的孩子或从他们那里抢东西(就像你的情况一样)。重构代码以不同的方式执行此操作。也许在context
中提供一个二传手函数来设置你需要的任何深度子级的数据。
相关文章:
- 如何在未直接触发的情况下停止事件
- 在不使用JQuery的情况下隐藏DOM中的选定元素
- 在不使用jquery的情况下查找页面中的所有锚点并附加函数
- 在不打开聊天屏幕的情况下制作Zopim-ding代理
- 在不阻止默认行为的情况下检测IE10中的缩放
- 如何在不传递此信息的情况下查找被调用的元素
- 如何在不刷新页面的情况下更新显示框
- 有没有一种方法可以在控制台关闭的情况下让console.log()在IE中记录消息
- JavaScript-在手机上不工作的情况下,在外部单击时隐藏元素
- 在我的情况下,如何进行http请求
- 在不知道深度或父属性的情况下从对象中删除属性
- 在不破坏未定义函数的情况下,对多个视图使用单个js文件
- ROR:如何在不重新加载浏览器的情况下从控制器获取参数
- 如何在不影响其他元素的情况下扩展DIV
- 如何在内联依赖项并将图像转换为dataURI的情况下完全提取网页
- 是否可以在不渲染的情况下深度遍历 React 子项
- Node 的断言模块是否提供了一种在没有强制的情况下执行深度相等检查的方法?
- history.js可以在没有哈希或的情况下进行URL深度链接吗?性格
- 如何在没有递归的情况下迭代n级深度的数组
- Android -深度链接并不是在所有情况下和所有浏览器上都能工作