Prop
Inputs to a Component
are its props. The props for a given Component are the union of all arguments annotated with Prop
in your spec methods. The same prop can be defined and accessed in multiple lifecycle methods. The annotation processor will validate that the props are being used with the correct type and name.
For each unique prop defined on the spec, the annotation processor adds a setter method on the Component's Builder that has the same name as the prop. By default props are required but can be marked as optional. A prop can also be constrained further by setting it's resType.
The parent component sets the props when it creates the component in it's method. The props cannot be updated throughout the lifecycle of the component unless they are marked as dynamic. If the layout need to be updated, the parent has to create a new component and set new props. The props should be immutable since the layout can be calculated on multiple threads. Immutability of the props ensures that no thread safety issues can occur in the component hierarchy.
Creating Props:
@LayoutSpec
public class HeaderSpec {
@OnCreateLayout
static Component onCreateLayout(
ComponentContext c,
@Prop MyTitles title,
@Prop(varArg = imageUrl) List<String> urls,
@Prop(optional = true) boolean isSelected) {
if (urls.isEmpty()) {
return null;
}
return Column.create(c)
.paddingDip(YogaEdge.ALL, 8)
.backgroundColor(isSelected ? Color.WHITE : Color.GREEN)
.child(
Image.create(c)
.url(urls.get(0))
.marginDip(YogaEdge.BOTTOM, 4)
)
.child(
Text.create(c)
.text(title.getTitle())
.textSizeSp(16)
.marginDip(YogaEdge.BOTTOM, 4)
)
.child(
Text.create(c)
.text(title.getSubtitle())
.textSizeSp(12)
)
.build();
}
}
Notice how imageUrl
, title
and isSelected
are used to set properties on different components within the layout.
Setting Props:
@LayoutSpec
public class MyComponent {
@OnCreateLayout
static Component onCreateLayout(ComponentContext c) {
return Header.create(c)
.title(new MyTitles("title", "subtitle"))
.imageUrl("https://example.com/image.jpg")
.build();
}
}
See also
Functions
true
.