React 总结笔记

父传子

props 传数据

1
2
3
4
5
6
7
8
9
10
11
12
13
import ClassProps from "./components/ClassProps";
import FunctionProps from "./components/FunctionProps";

function App() {
return (
<div className="App">
<ClassProps name="张三" age={18} />
<FunctionProps name="梨花" age={20} />
</div>
);
}

export default App;

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
import React from "react";

class ClassProps extends React.Component<{
name?: string;
age?: number;
}> {
render() {
return (
<>
<div>{this.props.name}</div>
<div>{this.props.age}</div>
</>
);
}
}
// 设置默认值 可能会被弃用 https://twitter.com/dan_abramov/status/1133878326358171650
(ClassProps as any).defaultProps = {
name: "John Doe",
age: 30,
};
export default ClassProps;

interface FunctionProps {
name: string;
age: number;
}
// 设置默认值
FunctionProps.defaultProps = {
name: "",
age: 0,
};
function FunctionProps(props: FunctionProps) {
return (
<div>
<h1>Function Props</h1>
<p>{props.name}</p>
<p>{props.age}</p>
</div>
);
}

export default FunctionProps;

children 传元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function App() {
return (
<div className="App">
<ClassChildren>
<div>
<p>我是子组件</p>
</div>
</ClassChildren>
<FunctionChildren>
<div>
<p>我是子组件</p>
</div>
</FunctionChildren>
</div>
);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React from "react";

class ClassChildren extends React.Component {
render() {
return <div id="ClassChildren">{this.props.children}</div>;
}
}

export default ClassChildren;

import { ReactChild, ReactFragment, ReactPortal } from "react";

function FunctionChildren(props: {
children: ReactChild | ReactFragment | ReactPortal;
}) {
return (
<div>
<h1>Function Children</h1>
<p>{props.children}</p>
</div>
);
}

export default FunctionChildren;

context