通過單擊 Button 它應該將checked狀態更改為true并應用選中的樣式,在我的情況下這沒有發生。如何更改映射組件的狀態?在給定的示例中,我有 3 個選項,但我將有 20 多個
export function Test() {
const [checkedState, setChecked] = React.useState(false);
const handleChange = () => {
setChecked((checked) => !checked);
};
<View>
<ButtonList
options={[
{ label: "Label", value: "value" },
{ label: "Label", value: "value2" },
{ label: "Label", value: "value3" },
]}
/>
</View>
);
}
我在這里映射
type Option = {
label: string;
value: string;
};
type ButtonListProps = {
options: Option[];
value: string;
};
export function ButtonList({ options, value }: ButtonListProps) {
return (
<View>
{options.map((option) => (
<Button
checked={checkedState}
onChange={handleChange}
onPress={ignore}
key={option.value}
label={option.label}
/>
))}
</View>
);
}
我的按鈕組件
type ButtonProps = {
checked: boolean;
label?: string;
onPress?: () => void;
onChange?: () => void;
};
export function Button({ checked, label, onPress, onChange }: ButtonProps) {
return (
<Pressable
onPress={onPress}
onChange={onChange}
>
<View style={checked && {backgroundColor: "red"} />
<Text>{label}</Text>
</Pressable>
);
}
uj5u.com熱心網友回復:
checkedState必須是狀態陣列而不是布林值
const [checkedState, setChecked] = React.useState([false,false,false]);
并且您的handleChange函式應該有一個名為 index 的引數
const handleChange = (index) => {
const newState = [...checkedState]
newState[index] = !newState[index]
setChecked(newState);
};
所以你的地圖應該像
{options.map((option,index) => (
<Button
checked={checkedState[index]}
onChange={()=>handleChange(index)}
onPress={ignore}
key={option.value}
label={option.label}
/>
))}
編輯1:如果你有動態選項,你可以這樣做
const options = [
{ label: "Label", value: "value" },
{ label: "Label", value: "value2" },
{ label: "Label", value: "value3" },
]
const [checkedState, setChecked] = React.useState(options.map(()=>false));
不要忘記將選項變數傳遞給ButtonList組件:
<ButtonList
options={options}
/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/521115.html
標籤:反应反应式反应钩子状态
上一篇:禁用觸摸屏的子視圖的可觸摸性
下一篇:無法加載配置類:net.guides.springboot2.crud.JPAspringboot中的應用程式錯誤
