🤖 Compose
[Compose] Slot API
콩드로이드
2025. 1. 6. 16:26
- Composable 내에서 다른 Composable을 사용할 수 있도록 하는 패턴
@Composable
fun MyCustomCard(
title: String,
content: @Composable () -> Unit // Slot API를 사용하여 Composable을 매개변수로 받음
) {
Card {
Column {
Text(text = title)
content() // 전달된 Composable을 호출
}
}
}
@Composable
fun MyScreen() {
MyCustomCard(title = "Hello") {
Text("This is the content of the card.") // Slot에 전달된 Composable
}
}
보통 content를 마지막 인자로 받아서 사용하는 경우가 많다
➡️ 고정된 ui를 가지지 않기에 유연성 , 재사용성에서 좋다
만약 content를 받지 않는다면 Text는 고정이 되므로, 좋지 않은 방식이다
@Composable
fun MyCustomCard(title: String) {
Card {
Column {
Text(text = title)
Text("This is the fixed content of the card.") // 고정된 내용
}
}
}
@Composable
fun MyScreen() {
MyCustomCard(title = "Hello") // 이제 content를 전달할 필요 없음
}
만약 특정 Scope에서만 동작하는 composable함수라면
@Composable
fun MyCustomCard(
title: String,
content: @Composable RowScope.() -> Unit // RowScope를 사용하여 Composable을 매개변수로 받음
)
위와 같이 content에 RowScope 혹은 ColumnScope를 지정할 수도 있다
재사용성이 높아지도록 위임할 수 있는 것들은 최대한 위임해주는 게 좋다