DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="./global.css" />
<script src="./lib/babel.standalone.js">script>
<script type="text/babel" data-type="module">
import React, { useState, useEffect, version as ReactVersion } from "./lib/react.js";
import { render, version as ReactDomVersion } from "./lib/react-dom.js";
import cls from "./lib/classnames.js";
const fetchJson = (url, fn) => {
fetch(url)
.then((response) => response.json())
.then((data) => fn(data));
};
let App = () => {
const [personList, setPersonList] = useState([]);
const [highlightList, setHighlightList] = useState([false]);
const [selected, setSelected] = useState(null);
const [bio, setBio] = useState("");
const toggleHighlight = (index) => {
setHighlightList((a) => {
let data = [...a];
data[index] = !data[index];
return data;
});
};
const select = (index) => {
setSelected(index);
for (const item of personList) {
if (item.id == index) {
setBio(item.company.bs);
break;
}
}
};
useEffect(() => {
fetchJson("https://jsonplaceholder.typicode.com/users", (data) => {
setPersonList(data.slice(0, 5));
});
}, []);
return (
<main>
<Button>click</Button>
<p>
<span>React: {ReactVersion}</span> <span>ReactDom: {ReactDomVersion}</span>
</p>
{personList.map((item, index) => {
return (
<Person
name={item.name}
highlight={highlightList[item.id] ?? false}
onToggle={() => toggleHighlight(item.id)}
onSelect={() => select(item.id)}
selected={selected === item.id}
/>
);
})}
{bio && <div className="bio">{bio}</div>}
</main>
);
};
const Person = (props) => {
return (
<div
onClick={(e) => {
e.stopPropagation();
props.onSelect();
}}
className={cls("person", { highlight: props.highlight }, { selected: props.selected })}
>
<p>{props.name}</p>
<input
type="checkbox"
checked={props.highlight}
onClick={(e) => {
e.stopPropagation();
props.onToggle();
}}
/>
</div>
);
};
render(<App />, document.querySelector("#app"));
script>
head>
<body>
<main id="app" />
body>
html>

- 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
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110