Mahiru's Humble Abode       博  客   时 间 线   归  档   关 于 与 友 链



React
Published on Fri Sep 17 2021 12:00:01 GMT+0000

创建一个函数组件

1
2
3
4
5
6
7
const Hello = (props)=>{
return <div>
Hello,{props.name}
</div>

}

export default Hello;

传参方法

父组件

1
2
3
4
5
6
7
import Hello from './components/hello/Hello'

const Page = ()=>{
return <Hello name={"world"}/>
}

export default Page;

子组件

1
2
3
4
5
6
7
const Hello = (props)=>{
return <div>
Hello,{props.name}
</div>

}

export default Hello;

参数传递函数(使用Hook)

父组件

1
2
3
4
5
6
7
8
9
import React, { useState } from 'react';
import Hello from '../Hello/Hello';

const Page = ()=>{
const [count,setCount] = useState(0);
return <Hello setCount={setCount} count={count}/>
}

export default Page;

子组件

1
2
3
4
5
6
7
const Hello = (props) => {
return <div onClick={() => { props.setCount(props.count + 1) }
}>Hello,count is{props.count}
</div>

}

export default Hello;

使用Hook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import React, { useState } from 'react';

function Example() {
// 声明一个新的叫做 “count” 的 state 变量
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>

);
}

使用 Effect Hook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React, { useState, useEffect } from 'react';

function Example() {
const [count, setCount] = useState(0);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>

);
}