## 📚 技术栈背景 | Technology Stack
- 列出所有的相关技术栈和使用的语言
- React
- [[TypeScript]]
- 你记录的这张卡是关于什么的?在什么样的场景下你会再次回到这张卡?
- 当 parent 传递信息给 child 时,用 Props,传递数据。
- 当 child 发回信息给 parent 时,用 callbacks,传递信息或触发事件。
- 相关文档
- [Passing Props to a Component – React](https://react.dev/learn/passing-props-to-a-component)
## 基本概念和信息
React 的特性之一是:单向数据流(Unidirectional Data Flow)
- Parent → Child:数据总是从 Parent 流向 Child,用 **Props** 的方式。
- Child → Parent:props 是只读的,Child 不能直接修改,要通过 **callbacks** 请求更改。
- Props
- 子组件不能直接修改
## 总体工作流程
### Props:Parent → Child
1. 在 Parent component file 中
- 定义数据
- 可以是 variable
- 可以是 state
- 可以是 function
- function 命名建议用 `handle` 前缀
```TSX
import { useState } from 'react';
function ParentComponent() {
// 1. 定义要传递的数据
const [message, setMessage] = useState('Hello');
// 2. 定义要传递的函数
const handleAction = (data: string) => {
console.log('Received:', data);
// 做一些操作
};
return (
<ChildComponent
message={message} // 传递数据
onAction={handleAction} // 传递函数
/>
);
}
```
2. 在 Child component file 中
1. 定义 Props interface(接口)
2. 使用 Props
```TSX
// 1. 定义props接口
interface ChildProps {
message: string;
onAction: (data: string) => void;
}
// 2. 使用解构接收props
function ChildComponent({ message, onAction }: ChildProps) {
return (
<View>
<Text>{message}</Text>
<Button
title="Click Me"
onPress={() => onAction('Some data')}
/>
</View>
);
}
```
### Callback:Child → Parent
1. 在 Parent component file 中:
- 准备接收数据
- 准备状态储存
- 准备 callback function
```TSX
function ParentComponent() {
// 1. 准备状态存储子组件传来的数据
const [childData, setChildData] = useState('');
// 2. 准备回调函数
const handleChildData = (data: string) => {
setChildData(data);
// 可以进行其他操作
};
return (
<View>
<Text>Child said: {childData}</Text>
<ChildComponent onDataSend={handleChildData} />
</View>
);
}
```
2. 在 Child component file 中
1. 准备要发送的数据
2. 在需要的时候调用回调函数
```TSX
interface ChildProps {
onDataSend: (data: string) => void;
}
function ChildComponent({ onDataSend }: ChildProps) {
// 1. 准备要发送的数据
const [inputText, setInputText] = useState('');
// 2. 在需要的时候调用回调函数
const handleSubmit = () => {
onDataSend(inputText); // 调用父组件传来的函数
};
return (
<View>
<TextInput
value={inputText}
onChangeText={setInputText}
/>
<Button
title="Send to Parent"
onPress={handleSubmit}
/>
</View>
);
}
```