Reactjs - 从应用程序的任何位置获取组件 [英] Reactjs - Get a component from anywhere in the app

查看:86
本文介绍了Reactjs - 从应用程序的任何位置获取组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法通过使用某种类型的id或类型来获取组件,就像在DOM操作中一样。类似于:

I'd like to know if there is a way to get a component by using some type of id, or by type, similar as you would do in DOM manipulation. Something like:

var Avatar = React.createClass({
    render: function () {
        ...
    }
});
React.renderComponent(Avatar({id:'avatar'}), ...);
...
...
var avatar = React.getComponentById('avatar');
avatar.setProps({url = 'http://...'});
// or
var avatars = React.getComponentByType('Avatar'); 
if (avatars.length) {
    avatars[0].setProps({url = 'http://...'});
}

我不想保留组件实例的引用......

I don't want to keep references of components instances...

推荐答案

setProps 是你应该谨慎使用的东西。事实上,存储对渲染组件的引用通常可能表明您可以以不同方式构造代码。我们还将 setProps 的使用限制为顶级组件。

setProps is something that you should use sparingly. In fact storing references to "rendered" components in general might indicate that you can structure your code differently. We also limit your uses of setProps to top level components.

var avatar = React.renderComponent(<Avatar .../>, node);
avatar.setProps({ foo: '1' });

等同于此,与声明性模型相比更好一些:

is equivalent to this, which fits in a bit better with the declarative model:

React.renderComponent(<Avatar .../>, node);
React.renderComponent(<Avatar ... foo="1" />, node);

你可以在函数调用中包装该渲染,这样你就可以随意调用它。

You could wrap that render up inside a function call so you could call it at will.

这篇关于Reactjs - 从应用程序的任何位置获取组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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