简体   繁体   English

通过ref或prop改变React中的子组件?

[英]Change child component in React via ref or prop?

Say I have a child component. 说我有一个儿童组件。 Let's say I want to change its height based on information that the parent has. 假设我想根据父母的信息改变其高度。

If I get a reference to it. 如果我得到它的参考。 I can change it with 我可以改变它

myChild.changeHeight(newHeight);

(see React.js - access to component methods ) (请参阅React.js - 访问组件方法

or I could change it with 或者我可以改变它

<Child height={newHeight}/>

Both could be changed in the render() method. 两者都可以在render()方法中更改。 But which one should I use? 但是我应该使用哪一个?

React team gave few scenarios where we should be using refs. React团队提供了几个我们应该使用refs的场景。

There are a few good use cases for refs: refs有一些很好的用例:

  • Managing focus, text selection, or media playback. 管理焦点,文本选择或媒体播放。
  • Triggering imperative animations. 触发势在必行的动画。
  • Integrating with third-party DOM libraries. 与第三方DOM库集成。

Avoid using refs for anything that can be done declaratively. 避免使用refs来做任何可以声明性地完成的事情。

If there is a possibility to do some functionality even without using refs, then go ahead and do it. 如果即使不使用ref也可以执行某些功能,那么请继续执行。 In your case, as you said, you have a way to do it by passing a prop. 在你的情况下,正如你所说,你可以通过传递道具来做到这一点。 It would be better if we use props itself rather than ref. 如果我们使用道具而不是ref,那会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM