Passing Data with Props
メニューを表示するにはスワイプしてください
Modern frontend applications are usually built from many reusable components. Instead of hardcoding content directly inside each component, developers often pass data from one component to another.
In Svelte, this is done using props.
What Are Props?
Props are values passed into a component from its parent component. They allow components to become flexible and reusable.
For example, a product card component could receive a title, price, image, or description. Instead of creating separate components for every product, the same component can display different data using props.
Creating a Component
Inside the src folder, create a new file called ProfileCard.svelte.
Add the following code:
<script>
export let name;
export let role;
</script>
<div class="card">
<h2>{name}</h2>
<p>{role}</p>
</div>
<style>
.card {
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
}
</style>
The export let syntax creates props that can receive values from another component.
Passing Data into the Component
Now open App.svelte and import the component:
<script>
import ProfileCard from './ProfileCard.svelte';
</script>
<ProfileCard
name="Alex Johnson"
role="Frontend Developer"
/>
The values passed into the component become available through the props.
Reusable Components
One of the biggest advantages of props is reusability.
You can create multiple cards using the same component while displaying different content.
<ProfileCard
name="Emma Wilson"
role="UI Designer"
/>
<ProfileCard
name="Michael Brown"
role="Backend Developer"
/>
This approach helps developers build scalable frontend applications more efficiently.
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください