[英]In React Native, is there a way to change the color of the button based on a boolean from a database?
[英]React Native - change color based on api value
我正在制作一個 React Native 項目,基本上,我想根據 api 的值更改樣式化的組件背景顏色,但不知道我將如何做到這一點
(我正在使用:React Native、Expo、typescript 和樣式組件)
如果API中的 levelRiskMorse 等於“NoRisk”,我希望ContainerRating (這是一個樣式化的組件)背景變為綠色
這是 api服務器。json :
"allTasks": [
{
"patientName": "PacientOne",
"taskName": "Walk",
"executors": "Person3 - Doctor",
"institutionName": "IntitutionName",
"generalObservations": "Observations Test",
"planType": "1588",
"time": "07:00",
"risk": true,
"levelRiskMorse": "NoRisk",
"levelRiskBarden": "Low"
},
這是假的 API !
組件本身和 styles.ts:
[...]
const [risk, setRisk] = useState('');
//fetching data
useEffect(() => {
async function getRiskLevel(){
const { data } = await api.get('allTasks');
const response = data.forEach((item: any | undefined) => {
return item.levelRiskMorse
})
setRisk(response);
}
getRiskLevel();
}, [])
return(
<View>
<ContainerRating> // if levelRiskMorse === "NoRISK" color turn to green
<Text>Sem Risco</Text>
<Text>0-24</Text>
</ContainerRating>
</View>
)
}
export const ContainerRating = styled.View`
border-width: 0.6px;
border-color: ${({theme}) => theme.colors.default_color};
flex-direction: row;
justify-content: space-around;
height: 50px;
align-items: center;
margin-top: 2px;
border-left: unset;
`;
對不起,如果我沒有說清楚,我不習慣在這里提問
簡單地做類似的事情:
<ContainerRating style={{color: levelRiskMorse==="NoRISK" ? 'green' : defaultColor }}
<Text>Sem Risco</Text>
<Text>0-24</Text>
</ContainerRating>
發生了什么? 我直接在組件中應用樣式 object (每個組件都有這個屬性)。 levelRiskMorse==="NoRISK"
這是一個 if 條件內聯。 如果為真,將設置“綠色”,否則為您要使用的默認顏色變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.