Ember模板-在函数调用中将参数从子级传递给父级



我有一个在循环中创建的Ember组件。我传递一个带有参数的函数。子级需要传递另一个参数,函数才能工作。我该如何做到这一点?

例如:

Parent:
<div>
{{#each items as |item index|}}
<Child 
@onButton1Click={{fn this.doStuff index}} // need index to do stuff
/>
{{/each}}
</div>
Child:
<div>
<ColorSelector @onColorChange={{this.changeColor}}/>
<Button @onClick={{this.onButton1ClickAction}} />
</div>
// Parent.js
@action
doStuff(index, color) {
// calculate stuff using color and index
}
// Child.js
@tracked
color = 'blue';
@action 
changeColor(passedColor) {
this.color = passedColor; // some hex value
}
@action
onButton1ClickAction() {
this.args.onButton1Click?.(this.color);
// how do I pass back color
}

问题是,如何使用子项的传递颜色并维护父项的索引?目前只看到索引。

看起来像

<Child 
onButton1Click={{fn this.doStuff index}} // need index to do stuff
/>

应该是

<Child 
@onButton1Click={{fn this.doStuff index}} // need index to do stuff
/>

<ColorSelector onColorChange={{this.changeColor}}/>
<Button onClick={{this.onButton1ClickAction}} />

应该是

<ColorSelector @onColorChange={{this.changeColor}}/>
<Button @onClick={{this.onButton1ClickAction}} />

(注意@(

如果没有@onButton1Click将被解释为html属性,该属性将应用于Child中具有...attributes的元素(如果存在(,否则onButton1Click将不会执行任何操作。

相关文件:https://guides.emberjs.com/release/components/component-arguments-and-html-attributes/

我认为您只需要从子执行父函数

//child.js
@tracked
color = 'blue';
@action 
changeColor(passedColor) {
this.color = passedColor; // some hex value
}
@action
onButton1ClickAction() {
const click = this.args.onButton1Click ?? null;
if (click) {
click(this.color)
}