简体   繁体   English

通过props与方法调用反应传递数据

[英]React passing data via props vs method call

Say I have a component X which renders a text input field + a child component Y. Y uses the text from the input field to render something else. 假设我有一个呈现文本输入字段的组件X +一个子组件Y。Y使用输入字段中的文本来呈现其他内容。

To get the data, X listens for a change event from the text field, and then grabs its updated content via a ref. 为了获取数据,X侦听来自文本字段的change事件,然后通过引用获取其更新的内容。

Now as I understand it I can pass the data to child Y in two ways. 现在,据我所知,我可以通过两种方式将数据传递给子Y。

1) X stores the new data in its state, so its render method is triggered, and here I pass the data to Y using props like <Y something={data}/> 1)X将新数据存储在其状态下,因此触发了其渲染方法,这里我使用<Y something={data}/>道具将数据传递给Y

2) X calls a method on Y by using it ref like this.refs.y.setSomething(data) . 2)X通过使用ref这样的ref在Y上调用方法,例如this.refs.y.setSomething(data) In this case I don't need to store the data in the state of X. 在这种情况下,我不需要以X状态存储数据。

So apart from storing state in X, what are the reasons to choose one over the other? 因此,除了将状态存储在X中之外,还有什么理由选择一个?

You should pass the data into the child component using props, as in the documentation . 您应该使用props将数据传递到子组件中,如文档所述 You can think of the props as the function arguments for the child components. 您可以将props作为子组件的功能参数。

Other than being the idiomatic way to do this in React, I can think of a few reasons why you should do this. 除了作为React中惯用的方式之外,我还能想到一些您为什么要这样做的原因。 Firstly, calling a method like this.refs.y.setSomething(data) will mean that you need to implement code for storing the state in Y. So you haven't had to set state in X, but you do it in Y instead. 首先,调用诸如this.refs.y.setSomething(data)类的方法将意味着您需要实现将状态存储在Y中的代码。因此,您不必在X中设置状态,而是在Y中进行设置。

More importantly, if X for some reason unmounts Y during a re-render and then later remounts it, you will have lost the state in Y. But if you are passing in props, then Y would receive the same props before and after it's unmounted. 更重要的是,如果X由于某种原因在重新渲染期间卸载了Y,然后又重新安装,则您将失去Y的状态。但是,如果您传递的是道具,那么Y在卸载之前和之后都会收到相同的道具。 。

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

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