[英]How to access child component from parent component in Ember
The concept is fairly simple.这个概念相当简单。
Assume I have a child component with its own separate js and hbs.假设我有一个子组件,它有自己独立的 js 和 hbs。 Child-component.hbs =>
子组件.hbs =>
<Button options = {{listOptions}} selected={{selectedOption}}
> Submit <Button
Child-component.js子组件.js
listOptions =[{id: 124, name: 'Mywork'}
selected => performing an action after getting the value from hbs selection.
Now I'm importing this into another component Main-component.hbs
like this现在我将它导入到另一个组件
Main-component.hbs
,就像这样
<ChildComponent />
This is rendering as expected with options and all, but based on the selectedOption
I want to do something in my main component.这是使用选项和所有选项按预期呈现的,但是基于
selectedOption
我想在我的主要组件中做一些事情。 Handling the action in the Main-component is not an option for me as its not what I was told to do.处理主组件中的操作对我来说不是一个选项,因为它不是我被告知要做的。 Is it possible to access
selectedOption
from the main-component?是否可以从主组件访问
selectedOption
? Kindly help.请帮忙。
Please note that I want to achieve this in Octane version.请注意,我想在 Octane 版本中实现这一点。
the only way to do this is to specifically pass a reference from the parent to the child, and have the child invoke some function on the parent (because, in rendering, data only flows down by default ("data down, actions/functions up"))这样做的唯一方法是专门将父项的引用传递给子项,并让子项在父项上调用一些 function(因为在渲染中,默认情况下数据仅向下流动(“数据向下,动作/功能向上“))
Example:例子:
class Parent {
foo(child) {
// do something with the child
}
}
<Child @foo={{this.foo}} />
// ------------------
class Child { }
{{ (@foo this) }}
Note that this is an "effect", and effects are generally a code-smell (derived data should be used whenever possible)请注意,这是一种“效果”,效果通常是代码味(应尽可能使用派生数据)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.