有没有办法获取所有的bar
<Wrapper/>
中的属性在“静态”下方,例如没有渲染?
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'));
这是一个尝试迭代 child.children
的简单尝试的 webpackbin这显然是行不通的,但如果有帮助的话,它就在这里:
http://www.webpackbin.com/EySeQ-ihg
最佳答案
TL;DR; 不,那不可能。
--
我曾经遇到过同样的问题,试图遍历一棵嵌套很深的子树。这是我的独家新闻:
所需知识
children
jsx
里面放的是什么打开和关闭标签,或直接注入(inject) children Prop 。除此之外children
Prop 将是undefined
.<div className="wrapper"> // Children <img src="url" /> </div> /* OR */ <div classname="wrapper" children={<img src="url" />}>
children
是一个不透明的树状数据结构,表示 react 元素的树,它可能是React.createElement
的输出那jsx
转译时实现。{ $$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
处理自己在幕后。
遍历 child
让我们以你的例子为例,尝试遍历整棵树。
<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
由于你现在应该知道的原因, Prop 是空的。到达它的子元素的唯一方法是使用它的 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>;
);
}
}
这显然根本不需要考虑。
结论
没有干净的方法来扩充深度嵌套的 child 或从他们那里获取一些东西(比如你的情况)。重构您的代码以不同的方式做到这一点。也许在 context
中提供一个 setter 函数设置您需要的来自任何深层 child 的数据。
关于javascript - 是否可以在不渲染的情况下深度遍历 React Children?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930825/