Flex
flex.tsx
import React from "react";import { StyleSheet, Text, View } from "react-native";const Flex = () => {return (<View style={[styles.container, {// Try setting `flexDirection` to `"row"`.flexDirection: "column"}]}><View style={{ flex: 1, backgroundColor: "red" }} /><View style={{ flex: 2, backgroundColor: "darkorange" }} /><View style={{ flex: 3, backgroundColor: "green" }} /></View>);};const styles = StyleSheet.create({container: {flex: 1,padding: 20,},});export default Flex;
app.tsx
import React from 'react'import Flex from './Flex';const App = () => {return (<Flex />);}export default App;
Flex Direction
FlexDirectionBasics.tsx
import React, { useState } from "react";import { StyleSheet, Text, TouchableOpacity, View } from "react-native";const FlexDirectionBasics = () => {const [flexDirection, setflexDirection] = useState("column");return (<PreviewLayoutlabel="flexDirection"values={["column", "row", "row-reverse", "column-reverse"]}selectedValue={flexDirection}setSelectedValue={setflexDirection}><Viewstyle={[styles.box, { backgroundColor: "powderblue" }]}/><Viewstyle={[styles.box, { backgroundColor: "skyblue" }]}/><Viewstyle={[styles.box, { backgroundColor: "steelblue" }]}/></PreviewLayout>);};const PreviewLayout = ({label,children,values,selectedValue,setSelectedValue,}) => (<View style={{ padding: 10, flex: 1 }}><Text style={styles.label}>{label}</Text><View style={styles.row}>{values.map((value: string) => (<TouchableOpacitykey={value}onPress={() => setSelectedValue(value)}style={[styles.button,selectedValue === value && styles.selected,]}><Textstyle={[styles.buttonLabel,selectedValue === value && styles.selectedLabel,]}>{value}</Text></TouchableOpacity>))}</View><View style={[styles.container, { [label]: selectedValue }]}>{children}</View></View>);const styles = StyleSheet.create({container: {flex: 1,marginTop: 8,backgroundColor: "aliceblue",},box: {width: 50,height: 50,},row: {flexDirection: "row",flexWrap: "wrap",},button: {paddingHorizontal: 8,paddingVertical: 6,borderRadius: 4,backgroundColor: "oldlace",alignSelf: "flex-start",marginHorizontal: "1%",marginBottom: 6,minWidth: "48%",textAlign: "center",},selected: {backgroundColor: "coral",borderWidth: 0,},buttonLabel: {fontSize: 12,fontWeight: "500",color: "coral",},selectedLabel: {color: "white",},label: {textAlign: "center",marginBottom: 10,fontSize: 24,},});export default FlexDirectionBasics;
注意看自定义组件的写法,以及 useState 的用法。
import React from 'react'import FlexDirectionBasics from './FlexDirectionBasics';const App = () => {return (<FlexDirectionBasics />);}export default App;
