样式与布局
RN 组件和 React Web 完全一样:函数组件 + useState 状态 + props 传参。会 React 就掌握了一半 RN。
useState
const [count, setCount] = useState(0),点按钮 setCount(count + 1),界面更新。
props
父组件传数据,子组件接收渲染。重复界面抽成组件复用。
注意事项
setState 是异步的;组件卸载后别 setState(会警告);状态提升到公共父组件共享数据。
代码示例
import { useState } from "react";
import { View, Text, Button, StyleSheet } from "react-native";
const Counter = () => {
const [count, setCount] = useState(0);
return (
<View style={styles.box}>
<Text style={styles.num}>{count}</Text>
<Button title="+1" onPress={() => setCount(count + 1)} />
</View>
);
};
// 子组件接收 props
const Greeting = ({ name }) => (
<Text style={styles.greet}>你好,{name}!</Text>
);
const App = () => {
return (
<View style={styles.container}>
<Greeting name="张三" />
<Counter />
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: "center", alignItems: "center" },
box: { alignItems: "center", marginTop: 20 },
num: { fontSize: 40, marginBottom: 8 },
greet: { fontSize: 18 }
});
export default App;
📚 JavaScript 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
let x = 1; | 声明变量(可重新赋值) |
const y = 2; | 声明常量(不可重新赋值) |
var 已过时 | 旧式变量声明,建议用 let/const |
if (条件) { } else { } | 条件判断 |
for (let i = 0; i < n; i++) { } | 循环 |
while (条件) { } | 条件循环 |
function fn(a, b) { return a + b; } | 函数声明 |
const fn = (a) => a + 1; | 箭头函数 |
array.push(x) / pop() | 数组尾部添加 / 删除 |
array.map(fn) / filter(fn) | 数组映射 / 过滤 |
obj.key / obj["key"] | 访问对象属性 |
JSON.stringify(obj) | 对象转 JSON 字符串 |
JSON.parse(str) | JSON 字符串转对象 |
document.getElementById("id") | 按 id 取元素 |
document.querySelector("选择器") | 按选择器取第一个元素 |
element.textContent | 读写元素文本 |
element.innerHTML | 读写元素 HTML(慎用,防 XSS) |
element.addEventListener("click", fn) | 绑定事件 |
console.log(x) | 控制台输出(调试) |
setTimeout(fn, 1000) | 延迟执行(毫秒) |
window.location.href | 当前页面地址(可赋值跳转) |
localStorage.setItem("k", v) | 本地存储写入 |
localStorage.getItem("k") | 本地存储读取 |
new Promise((resolve, reject) => {}) | Promise 异步处理 |
async / await | 异步函数语法糖 |