Reacting to Input With State

https://react.dev/learn/reacting-to-input-with-state

Imperative Programming.
You have to write the exact instructions to manipulate the UI depending on what just happened.

声明式地考虑 UI,预先考虑有哪几种状态,
定义所有可能不同的状态。

考虑状态之间的转换。

Desription:

Make it so that clicking on the picture removes the background–active CSS class from the outer

, but adds the picture–active class to the . Clicking the background again should restore the original CSS classes.

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

export default function Picture() {
const [active, setActive] = useState(false)
return (
<div
className={`background ${active ? '' : 'background--active'}`}
onClick={() => setActive(false)}
>
<img
className={`picture ${active ? 'picture--active' : ''}`}
alt="Rainbow houses in Kampung Pelangi, Indonesia"
src="https://i.imgur.com/5qwVYb1.jpeg"
onClick={e => {
e.stopPropagation();
setActive(true)
}}
/>
</div>
);
}

Note: e.stopPropagation();

Ans Version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { useState } from 'react';

export default function Picture() {
const [isActive, setIsActive] = useState(false);

let backgroundClassName = 'background';
let pictureClassName = 'picture';
if (isActive) {
pictureClassName += ' picture--active';
} else {
backgroundClassName += ' background--active';
}

return (
<div
className={backgroundClassName}
onClick={() => setIsActive(false)}
>
<img
onClick={e => {
e.stopPropagation();
setIsActive(true);
}}
className={pictureClassName}
alt="Rainbow houses in Kampung Pelangi, Indonesia"
src="https://i.imgur.com/5qwVYb1.jpeg"
/>
</div>
);
}

Reacting to Input With State
https://www.hardyhu.cn/2024/12/22/Reacting-to-Input-With-State/
Author
John Doe
Posted on
December 22, 2024
Licensed under