2015-09-05 113 views
1

有没有方法按名称访问React组件?例如,使用React devtools,我可以搜索组件并使用$r访问控制台中最近选择的组件。有没有一种方法可以在没有React devtools的情况下访问这些组件?即有没有我可以用来抓取这些组件的查询?通过名称获取React组件

更多信息:我有兴趣为使用反应的特定网页编写Chrome扩展。我知道要与之交互的组件的名称,但我不确定如何实际访问它。

+0

为什么这是你的用例? – Pcriulan

+0

对不起,我应该更清楚。我添加了一些额外的信息。 – acidic

+0

在这种情况下,很难确切知道你指的是什么组件的名称 - 你没有澄清,也没有示例代码。 –

回答

1

这里有一个函数来遍历并转换为树结构的一个反应组件层次结构。刚刚接触组件的名称与c.constructor.name

const { 
    isDOMComponent, 
    getRenderedChildOfCompositeComponent, 
    findRenderedComponentWithType 
} = React.addons.TestUtils; 

function traverse(c, node) { 
    if (isDOMComponent(c)) { 
    return; 
    } 

    node.children.push({ 
    name: c.constructor.name, 
    children: [] 
    }); 

    const ccc = getRenderedChildOfCompositeComponent(c); 

    if (isDOMComponent(ccc)) { 
    React.Children.forEach(ccc.props.children, function traverseCompositeChildrenOf(child) { 
     if (child.type) { 
     const cccc = findRenderedComponentWithType(ccc, child.type); 
     traverse(cccc, getNode(node, c.constructor.name)); 
     } 
    }); 
    } else { 
    traverse(ccc, getNode(node, c.constructor.name)); 
    } 
} 

使用方法如下:

const root = React.render(<Root/>, document.createElement('div')); 

let tree = { 
    name, 
    children: [] 
}; 

let tree = traverse(root, tree); // your component hierarchy by name in a tree 

taken from this repo

1

如果你不想竖构图,你可以使用一个ref
否则它们是在子孙访问祖先组件的情况下作为道具传递的引用,或者在祖先访问子孙组件的情况下保持在范围中。

https://facebook.github.io/react/docs/more-about-refs.html 参考原则上允许更多的水平组合,但如果你正在做很多这个,你可能想要考虑你的数据模型,以及像Flux /单向数据流的实现。这实际上是来自文档的指针;他们建议您仔细考虑数据结构&状态。 (见https://facebook.github.io/react/docs/more-about-refs.html#cautions

在你的情况,我会建议有一个函数作为道具传递给所有组件,他们可以触发状态改变来设置最近查看的组件。你只需要传递一个唯一的ID作为道具。假设您可以控制要选择的组件的编程响应,则应该将所有组件都传递给驻留在共同祖先组件中的公共处理函数。它将作为唯一标识该组件的索引作为参数。该函数会更新状态,React将发出新的渲染周期。

+0

我已将更多信息添加到我的问题中。 – acidic