屏幕
配色方案
明暗
圆角
颜色
所有状态
- 何时出现
- 行为规则
把这 2 个文件放进 components/mobilens/。只依赖 react-native(已用 Expo SDK 58 检查)。
// Segmented control: two to five options in one row; the selected one sits on a sliding thumb.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState } from 'react';
import { AccessibilityInfo, Animated, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
export type Segment<T extends string> = { value: T; label: string };
export type SegmentedControlProps<T extends string> = {
/** Two to five options. Keep each label to one short word. */
options: Segment<T>[];
/** The selected option's value. */
value: T;
/** Called with the new value when another option is tapped. */
onChange: (value: T) => void;
/** Grey and cannot be changed. */
disabled?: boolean;
/** What screen readers call the whole control, such as "Time range". */
accessibilityLabel?: string;
};
type CopyInkProps = { copyTestIDs?: { optionPrefix?: string } };
export function SegmentedControl<T extends string>({ options, value, onChange, disabled = false, accessibilityLabel, copyTestIDs }: SegmentedControlProps<T> & CopyInkProps) {
const [width, setWidth] = useState(0);
const index = Math.max(0, options.findIndex((o) => o.value === value));
const segment = width ? (width - 4) / options.length : 0;
const x = useRef(new Animated.Value(0)).current;
const placed = useRef(false);
const still = useReduceMotion();
useEffect(() => {
if (!segment) return;
// The first placement and Reduce Motion jump; a change slides.
if (!placed.current || still) x.setValue(index * segment);
else Animated.spring(x, { toValue: index * segment, useNativeDriver: Platform.OS !== 'web', speed: 24, bounciness: 0 }).start();
placed.current = true;
}, [index, segment, still, x]);
return (
<View
style={[styles.track, disabled && styles.trackDisabled]}
onLayout={(e) => setWidth(e.nativeEvent.layout.width)}
accessibilityRole="tablist"
accessibilityLabel={accessibilityLabel}
>
{segment ? <Animated.View style={[styles.thumb, disabled && styles.thumbDisabled, { width: segment, transform: [{ translateX: x }] }]} /> : null}
{options.map((o, i) => {
const on = o.value === value;
return (
<Pressable
key={o.value}
onPress={disabled || on ? undefined : () => onChange(o.value)}
disabled={disabled}
accessibilityRole="tab"
aria-selected={on}
accessibilityState={{ selected: on, disabled }}
style={({ pressed }) => [styles.segment, pressed && !on && styles.pressed]}
>
<Text testID={copyTestIDs?.optionPrefix ? copyTestIDs.optionPrefix + i : undefined} style={[styles.label, on && styles.labelOn, disabled && styles.labelDisabled]} numberOfLines={1}>{o.label}</Text>
</Pressable>
);
})}
</View>
);
}
function useReduceMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((on) => live && setReduce(on));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce);
return () => {
live = false;
sub.remove();
};
}, []);
return reduce;
}
const styles = StyleSheet.create({
track: { flexDirection: 'row', padding: 2, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
trackDisabled: { opacity: 0.6 },
thumb: {
position: 'absolute',
top: 2,
bottom: 2,
left: 2,
borderRadius: radius.md,
backgroundColor: colors.surface,
shadowColor: colors.shadow,
shadowOpacity: 0.12,
shadowRadius: 3,
shadowOffset: { width: 0, height: 1 },
elevation: 2,
},
thumbDisabled: { shadowOpacity: 0, elevation: 0 },
segment: { flex: 1, minHeight: 36, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md, paddingHorizontal: 8 },
pressed: { opacity: 0.6 },
label: { fontSize: 15, fontWeight: '500', color: colors.onSurfaceVariant },
labelOn: { fontWeight: '600', color: colors.onSurface },
labelDisabled: { color: colors.onSurfaceVariant },
});
// Segmented control: two to five options in one row; the selected one sits on a sliding thumb.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState } from 'react';
import { AccessibilityInfo, Animated, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
export type Segment<T extends string> = { value: T; label: string };
export type SegmentedControlProps<T extends string> = {
/** Two to five options. Keep each label to one short word. */
options: Segment<T>[];
/** The selected option's value. */
value: T;
/** Called with the new value when another option is tapped. */
onChange: (value: T) => void;
/** Grey and cannot be changed. */
disabled?: boolean;
/** What screen readers call the whole control, such as "Time range". */
accessibilityLabel?: string;
};
type CopyInkProps = { copyTestIDs?: { optionPrefix?: string } };
export function SegmentedControl<T extends string>({ options, value, onChange, disabled = false, accessibilityLabel, copyTestIDs }: SegmentedControlProps<T> & CopyInkProps) {
const [width, setWidth] = useState(0);
const index = Math.max(0, options.findIndex((o) => o.value === value));
const segment = width ? (width - 4) / options.length : 0;
const x = useRef(new Animated.Value(0)).current;
const placed = useRef(false);
const still = useReduceMotion();
useEffect(() => {
if (!segment) return;
// The first placement and Reduce Motion jump; a change slides.
if (!placed.current || still) x.setValue(index * segment);
else Animated.spring(x, { toValue: index * segment, useNativeDriver: Platform.OS !== 'web', speed: 24, bounciness: 0 }).start();
placed.current = true;
}, [index, segment, still, x]);
return (
<View
style={[styles.track, disabled && styles.trackDisabled]}
onLayout={(e) => setWidth(e.nativeEvent.layout.width)}
accessibilityRole="tablist"
accessibilityLabel={accessibilityLabel}
>
{segment ? <Animated.View style={[styles.thumb, disabled && styles.thumbDisabled, { width: segment, transform: [{ translateX: x }] }]} /> : null}
{options.map((o, i) => {
const on = o.value === value;
return (
<Pressable
key={o.value}
onPress={disabled || on ? undefined : () => onChange(o.value)}
disabled={disabled}
accessibilityRole="tab"
aria-selected={on}
accessibilityState={{ selected: on, disabled }}
style={({ pressed }) => [styles.segment, pressed && !on && styles.pressed]}
>
<Text testID={copyTestIDs?.optionPrefix ? copyTestIDs.optionPrefix + i : undefined} style={[styles.label, on && styles.labelOn, disabled && styles.labelDisabled]} numberOfLines={1}>{o.label}</Text>
</Pressable>
);
})}
</View>
);
}
function useReduceMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((on) => live && setReduce(on));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce);
return () => {
live = false;
sub.remove();
};
}, []);
return reduce;
}
const styles = StyleSheet.create({
track: { flexDirection: 'row', padding: 2, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
trackDisabled: { opacity: 0.6 },
thumb: {
position: 'absolute',
top: 2,
bottom: 2,
left: 2,
borderRadius: radius.md,
backgroundColor: colors.surface,
shadowColor: colors.shadow,
shadowOpacity: 0.12,
shadowRadius: 3,
shadowOffset: { width: 0, height: 1 },
elevation: 2,
},
thumbDisabled: { shadowOpacity: 0, elevation: 0 },
segment: { flex: 1, minHeight: 36, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md, paddingHorizontal: 8 },
pressed: { opacity: 0.6 },
label: { fontSize: 15, fontWeight: '500', color: colors.onSurfaceVariant },
labelOn: { fontWeight: '600', color: colors.onSurface },
labelDisabled: { color: colors.onSurfaceVariant },
});
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
用法
import { useState } from 'react';
import { SegmentedControl } from '@/components/mobilens/SegmentedControl';
type Plan = 'monthly' | 'yearly';
export function BillingPeriod({ onChange }: { onChange: (plan: Plan) => void }) {
const [plan, setPlan] = useState<Plan>('yearly');
return (
<SegmentedControl
accessibilityLabel="Billing period"
options={[
{ value: 'monthly', label: 'Monthly' },
{ value: 'yearly', label: 'Yearly' },
]}
value={plan}
onChange={(next) => {
setPlan(next);
onChange(next);
}}
/>
);
}
import { useState } from 'react';
import { SegmentedControl } from '@/components/mobilens/SegmentedControl';
type Plan = 'monthly' | 'yearly';
export function BillingPeriod({ onChange }: { onChange: (plan: Plan) => void }) {
const [plan, setPlan] = useState<Plan>('yearly');
return (
<SegmentedControl
accessibilityLabel="Billing period"
options={[
{ value: 'monthly', label: 'Monthly' },
{ value: 'yearly', label: 'Yearly' },
]}
value={plan}
onChange={(next) => {
setPlan(next);
onChange(next);
}}
/>
);
}
API
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| options | Segment<T>[] | – | Two to five options. Keep each label to one short word. |
| value | T | – | The selected option's value. |
| onChange | (value: T) => void | – | Called with the new value when another option is tapped. |
| disabled? | boolean | false | Grey and cannot be changed. |
| accessibilityLabel? | string | – | What screen readers call the whole control, such as "Time range". |
用在这些流程里
Add the "Segmented control" control to this Expo or React Native project. Create the files below with exactly this content. Do not restyle or rewrite them.
FILES
Put them in components/mobilens/. theme.ts is shared by every Mobilens component: if it already exists, keep one copy, and skip any other file that is already there with the same content. If the project has no "@/..." import alias, change those imports to relative paths.
--- components/mobilens/theme.ts ---
// Theme: Emerald, light, default corners. Shared by every Mobilens component; edit the values to match your app.
export const colors = {
background: '#fafafa',
surface: '#ffffff',
surfaceVariant: '#f4f4f5',
onBackground: '#18181b',
onSurface: '#18181b',
onSurfaceVariant: '#6b6b74',
outline: '#8a8a93',
outlineVariant: '#e4e4e7',
error: '#ba1a1a',
success: '#296b2a',
warning: '#b45309',
shadow: '#000000',
scrim: 'rgba(0,0,0,0.32)',
primary: '#006c50',
onPrimary: '#ffffff',
primaryContainer: '#82f8cb',
onPrimaryContainer: '#002116',
secondary: '#3e6374',
onSecondary: '#ffffff',
secondaryContainer: '#d8dfe2',
onSecondaryContainer: '#1c2d34',
tertiary: '#1f6862',
onTertiary: '#ffffff',
tertiaryContainer: '#d3e0df',
onTertiaryContainer: '#0e2f2c',
onError: '#ffffff',
onSuccess: '#ffffff',
onWarning: '#ffffff',
} as const;
export const radius = {
sm: 6,
md: 12,
lg: 20,
} as const;
--- end of theme.ts ---
--- components/mobilens/SegmentedControl.tsx ---
// Segmented control: two to five options in one row; the selected one sits on a sliding thumb.
// Works in Expo and bare React Native on iOS, Android and web. Depends only on react-native and ./theme.
import { useEffect, useRef, useState } from 'react';
import { AccessibilityInfo, Animated, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { colors, radius } from './theme';
export type Segment<T extends string> = { value: T; label: string };
export type SegmentedControlProps<T extends string> = {
/** Two to five options. Keep each label to one short word. */
options: Segment<T>[];
/** The selected option's value. */
value: T;
/** Called with the new value when another option is tapped. */
onChange: (value: T) => void;
/** Grey and cannot be changed. */
disabled?: boolean;
/** What screen readers call the whole control, such as "Time range". */
accessibilityLabel?: string;
};
type CopyInkProps = { copyTestIDs?: { optionPrefix?: string } };
export function SegmentedControl<T extends string>({ options, value, onChange, disabled = false, accessibilityLabel, copyTestIDs }: SegmentedControlProps<T> & CopyInkProps) {
const [width, setWidth] = useState(0);
const index = Math.max(0, options.findIndex((o) => o.value === value));
const segment = width ? (width - 4) / options.length : 0;
const x = useRef(new Animated.Value(0)).current;
const placed = useRef(false);
const still = useReduceMotion();
useEffect(() => {
if (!segment) return;
// The first placement and Reduce Motion jump; a change slides.
if (!placed.current || still) x.setValue(index * segment);
else Animated.spring(x, { toValue: index * segment, useNativeDriver: Platform.OS !== 'web', speed: 24, bounciness: 0 }).start();
placed.current = true;
}, [index, segment, still, x]);
return (
<View
style={[styles.track, disabled && styles.trackDisabled]}
onLayout={(e) => setWidth(e.nativeEvent.layout.width)}
accessibilityRole="tablist"
accessibilityLabel={accessibilityLabel}
>
{segment ? <Animated.View style={[styles.thumb, disabled && styles.thumbDisabled, { width: segment, transform: [{ translateX: x }] }]} /> : null}
{options.map((o, i) => {
const on = o.value === value;
return (
<Pressable
key={o.value}
onPress={disabled || on ? undefined : () => onChange(o.value)}
disabled={disabled}
accessibilityRole="tab"
aria-selected={on}
accessibilityState={{ selected: on, disabled }}
style={({ pressed }) => [styles.segment, pressed && !on && styles.pressed]}
>
<Text testID={copyTestIDs?.optionPrefix ? copyTestIDs.optionPrefix + i : undefined} style={[styles.label, on && styles.labelOn, disabled && styles.labelDisabled]} numberOfLines={1}>{o.label}</Text>
</Pressable>
);
})}
</View>
);
}
function useReduceMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
let live = true;
AccessibilityInfo.isReduceMotionEnabled().then((on) => live && setReduce(on));
const sub = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduce);
return () => {
live = false;
sub.remove();
};
}, []);
return reduce;
}
const styles = StyleSheet.create({
track: { flexDirection: 'row', padding: 2, borderRadius: radius.md, backgroundColor: colors.surfaceVariant },
trackDisabled: { opacity: 0.6 },
thumb: {
position: 'absolute',
top: 2,
bottom: 2,
left: 2,
borderRadius: radius.md,
backgroundColor: colors.surface,
shadowColor: colors.shadow,
shadowOpacity: 0.12,
shadowRadius: 3,
shadowOffset: { width: 0, height: 1 },
elevation: 2,
},
thumbDisabled: { shadowOpacity: 0, elevation: 0 },
segment: { flex: 1, minHeight: 36, alignItems: 'center', justifyContent: 'center', borderRadius: radius.md, paddingHorizontal: 8 },
pressed: { opacity: 0.6 },
label: { fontSize: 15, fontWeight: '500', color: colors.onSurfaceVariant },
labelOn: { fontWeight: '600', color: colors.onSurface },
labelDisabled: { color: colors.onSurfaceVariant },
});
--- end of SegmentedControl.tsx ---
HOW TO USE IT
import { useState } from 'react';
import { SegmentedControl } from '@/components/mobilens/SegmentedControl';
type Plan = 'monthly' | 'yearly';
export function BillingPeriod({ onChange }: { onChange: (plan: Plan) => void }) {
const [plan, setPlan] = useState<Plan>('yearly');
return (
<SegmentedControl
accessibilityLabel="Billing period"
options={[
{ value: 'monthly', label: 'Monthly' },
{ value: 'yearly', label: 'Yearly' },
]}
value={plan}
onChange={(next) => {
setPlan(next);
onChange(next);
}}
/>
);
}
STATES: all 3 must work in the screen where you use it
- Selected: when the screen opens with one option selected. Exactly one option is selected; the others are plain text on the track. The thumb is placed without sliding when the screen opens.
- Changed: when another option is tapped. The thumb slides to it; with Reduce Motion on it jumps. Tapping the selected option does nothing.
- Disabled: when the screen sets disabled, for example while it loads. Faded and cannot be changed.
ACCESSIBILITY
- Announced as tabs: each option says its label, selected or not, and its position.
- With Reduce Motion on, the thumb does not slide.
- Each option is at least 36 points tall and as wide as an equal share of the row.
WHEN YOU FINISH
List every state and rule above and say how you verified each one.