[英]React how to inline style different objects in one element
在React中,我試圖僅將樣式應用於像h1這樣的元素內的一個對象,這是一個示例
const Header = () => {
const firstName = "Ashraf";
const lastName = "Fathi";
const date = new Date();
const hours = date.getHours();
let timeOfDay;
const styles = {
color: ""
}
if (hours < 12) {
timeOfDay = "Good morning"
styles.color = "#ff474d"
}
else if (hours >= 12 && hours < 17) {
timeOfDay = "Good afternoon"
styles.color = "#7b5dff"
}
else {
timeOfDay = "Good night"
styles.color = "#01ff41"
}
return(
<div>
<h1 className="navbar" style={styles}>{timeOfDay} {`${firstName} ${lastName}`} It is currently {hours} clock</h1>
</div>
)
}
我想做的是將樣式僅應用於timeOfDay,所以我怎么能做到這一點? 我嘗試了不同的方法,但是所有這些都歸結為style = {},影響了整個不需要的元素。 提前致謝
在timeOfDay
周圍添加一個span
,然后timeOfDay
傳遞樣式
<div>
<h1 className="navbar"><span style={styles}>{timeOfDay}</span> {`${firstName} ${lastName}`} It is currently {hours} clock</h1>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.