React 之 Component 基礎

不要想的太複雜。

把東西傳給 Component:props

1
2
3
4
5
6
7
8
9
10
11
12
// 接收到 props 參數
function Person (props) {
return <div>{props.name} | {props.age} | {props.gender}</div>
}

ReactDOM.render(
<React.StrictMode>
// 傳進去 Component
<Person name="Peanu" age="20" gender="man"/>
</React.StrictMode>,
document.getElementById('root')
);

在 Component 裡面塞東西:children

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Person (props) {
return (
<div>
// 用 children 接收
{props.children} <br />
{props.name} | {props.age} | {props.gender}
</div>
)
}

ReactDOM.render(
<React.StrictMode>
<Person name="Peanu" age="20" gender="man">
// 夾在裡面
Hello
</Person>
</React.StrictMode>,
document.getElementById('root')
);

如果想寫成 <Component /> 的格式也行:

1
2
3
4
5
6
7
8
9
10
function Person ({ children }) {
return <div>{children}</div>
}

ReactDOM.render(
<React.StrictMode>
<Person children="helloooo" />
</React.StrictMode>,
document.getElementById('root')
);
mentor-program-day112 JSX 的原理
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×