寫多了taro, 看見react native中的組件好親切啊,幾乎一模一樣。
一、函數式組件 — 常用
1)無狀態,每次刷新都是生成一個新的狀態
2)基于狀態變化的管理
3)簡潔,代碼少,易于服用
import React from "react";
import { View, Text } from 'react-native';// 子組件 TestFunctionDemo.js
export default function TestFunctionDemo(props) {const { name, info: {age, sex} } = propsconst [address, setAddress] = useState('中國')useEffect(() => {// 第一次加載完成setTimeout(() => {setAddress('大陸')}, 2000)}, [])useEffect(() => {// 監聽address}, [address])return (<View style={{height: 200, width: '80%', padding: 20, borderRadius: 10, backgroundColor: '#ccc'}}><Text>我是子組件</Text><Text>姓名:{ name }</Text><Text>年齡:{ age }</Text><Text>性別:{ sex }</Text><Text>{`地址:${ address }`}</Text>{ props.children}</View>)
}// 簡寫
const TestFunctionDemo = (props) => {// ...
}
export default TestFunctionDemo// 或
export default (props) => {// ...
}
二、class組件
1) 有狀態state, 每次都是修改的同一個狀態
2) 基于生命周期的管理
// 子組件 TestClassDemo .js
class TestClassDemo extends React.Component {constructor(props) {super(props)this.state = {address: '中國'}}componentDidMount() {setTimeout(() => {this.setState({address: '大陸'})}, 2000)}render() {const { name, info: {age, sex} } = this.propsconst { address } = this.statereturn (<View style={{height: 200, width: '80%', padding: 20, borderRadius: 10, backgroundColor: '#ccc'}}><Text>我是子組件</Text><Text>姓名:{ name }</Text><Text>年齡:{ age }</Text><Text>性別:{ sex }</Text><Text>{`地址:${ address }`}</Text>{ this.props.children}</View>)}
}export default TestClassDemo
三、父組件引入
// 父組件app.js中引入
import TestFunctionDemo from './src/components/TestFunctionDemo';
import TestClassDemofrom './src/components/TestClassDemo';// ...
const info = {age: 20,sex: 'nan'
}// ...<TestFunctionDemo name="zhangsan" info={info}><Text>我是通過插槽加入的!</Text>
</TestFunctionDemo><TestClassDemo name="zhangsan" info={info}><Text>我是通過插槽加入的!</Text>
</TestClassDemo>
以上是不是和react一模一樣
四、樣式
!!!這里和react不一樣
import React from "react";
import { View, Text, StyleSheet } from 'react-native';// 子組件 TestFunctionDemo.js
export default (props) => {// ...return (<View style={styles.box}>// 多個樣式用數組<Text style={[styles.textLine, styles.title]}>我是子組件</Text><Text style={styles.textLine}>姓名:{ name }</Text>// ...</View>)
}// 樣式
const styles = StyleSheet.create({box: {height: 200, width: '80%', padding: 20, borderRadius: 10, backgroundColor: '#ccc'},textLine: {fontSize: 18,color: 'blue'},title: {fontWeight: "bold"}
})