【问题标题】:What is the react way of passing directives/Inputs to child in angular?以角度将指令/输入传递给孩子的反应方式是什么?
【发布时间】:2018-12-01 06:49:20
【问题描述】:

在 react 中,你可以简单地这样写:

<component {...props} /> 

将属性从父级传递给子级。我知道在角度您可以使用@Input 来接收和传递数据,但是您将如何处理动态指令列表以传递给子元素? 只是为了说明情况:

<custom-button [color]="color" [x]="some value" [y]="some other val"/>

您的自定义按钮应将所有这些输入传递给自定义按钮组件中的包装按钮元素。

【问题讨论】:

  • 在 Angular 中,你不需要。相关:stackoverflow.com/q/38122124/3001761.
  • 那么如何在不重复子组件可能拥有的每一个 API 的情况下组合组件呢?
  • 再一次,你没有。 React 和 Angular 是两个截然不同的东西,有着不同的目标和理念。
  • @jonrsharpe 我了解 Angular 中数据类型的限制。但我会更深入地研究这一点,因为我认为传递 var 是任何稍微复杂的软件系统的基本方面,在 Angular 中应该有一种方法。

标签: angular input angular6 react-props


【解决方案1】:

您可以通过多种方式做到这一点。例如,您可以有一个服务,例如 SharedComponentXStateService,在父子节点之间共享状态值。

更接近 React 功能的方法是拥有一个上下文变量,其中包含在父子节点之间共享的所有变量。在接受它的子节点上创建一个输入,并从父节点传递值。

/** context interface */
export interface IComponentXContext {
  color: string;
  x: string;
  y: string;
}

/** parent component */
@Component({
  template: <custom-button context="context" />
})
export class ParentXComponent {
  context: IComponentXContext = { color: 'red', x: 'x', y: 'y' }
}

/** child component */
@Component({
  selector: 'custom-button'
})
export class CustomButtonComponent {
  @Input()
  context: IComponentXContext;
}

【讨论】:

  • 我看到了它是如何与输入一起工作的,但不是指令
猜你喜欢
  • 2015-06-10
  • 1970-01-01
  • 2018-09-03
  • 2018-04-09
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多