通过名称获取 React 组件 [英] Getting React Component by name

查看:78
本文介绍了通过名称获取 React 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to access a React component by name? For example, using React devtools, I can search through components and access the most recently selected one in the console by using $r. Is there a way to access these components without React devtools? I.e. is there a query I can use to grab these components?

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

Some more information: I am interested in writing a chrome extension for a specific webpage that uses react. I know the name of the component I want to interact with, I'm just not sure how to actually access it.

推荐答案

这是一个函数,用于遍历 React 组件层次结构并将其转换为树结构.只需使用 c.constructor.name 访问组件的名称:

Here's a function to traverse and transform into a tree structure a react component hierarchy. Just access component's name with 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

取自这个 repo

这篇关于通过名称获取 React 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆