解決React報錯Style prop value must be an object
總覽
在React中,當我們?yōu)樵氐?code>style 屬性傳遞字符串時,會產(chǎn)生"Style prop value must be an object"警告。為了解決該警告,使用從屬性到值的映射。比如說,style={{paddingLeft: '15px'}}
。
這里有個例子來展示錯誤是如何發(fā)生的。
// App.js const App = () => { // ?? Style prop value must be an object eslint(react/style-prop-object) return ( <div> <h1 style="margin-left: 4rem">Hello world</h1> </div> ); }; export default App;
映射
上述代碼的問題在于,我們?yōu)?code>h1元素的style
屬性傳遞了字符串。相反,style
屬性應(yīng)該傳遞從屬性到值的映射。
const App = () => { return ( <div> <h1 style={{ marginLeft: '4rem', fontSize: '20px', padding: '20px', backgroundColor: 'salmon', color: 'white', }} > Hello world </h1> </div> ); }; export default App;
需要注意的是,這里我們使用了2對大括號。外側(cè)的大括號是對一個表達式的求值,內(nèi)側(cè)的大括號是包含屬性名稱和值的對象。
你還可以使用邏輯來計算特定的值。
const App = () => { return ( <div> <h1 style={{ marginLeft: 2 + 2 + 'rem', fontSize: Math.random() > 0.5 ? '20px' : '40px', padding: '20px', backgroundColor: 'salmon', color: 'white', }} > Hello world </h1> </div> ); }; export default App;
提取
你也可以將包含屬性和值的對象提取到一個變量中。
const App = () => { const h1Styles = { marginLeft: 2 + 2 + 'rem', fontSize: Math.random() > 0.5 ? '20px' : '40px', padding: '20px', backgroundColor: 'salmon', color: 'white', }; return ( <div> <h1 style={h1Styles}>Hello world</h1> </div> ); }; export default App;
需要注意的是,CSS屬性的命名必須是駝峰式。另一種方法是將你的CSS寫在一個以.css
為擴展名的文件中,并使用className
屬性來為你的元素聲明樣式。
下面是我們?nèi)绾螌?code>h1元素的樣式移到一個名為App.css
的文件中的一個類中。
.my-h1 { margin-left: 4rem; font-size: 20px; padding: 20px; background-color: salmon; color: white; }
然后,我們可以導入該css
文件,并使用my-h1
類。
import './App.css'; const App = () => { return ( <div> <h1 className="my-h1">Hello world</h1> </div> ); }; export default App;
這是對內(nèi)聯(lián)樣式的一種替代。需要注意的是,這個屬性被稱為className
而不是class
。原因是:class
是JavaScript中的一個保留詞。class
關(guān)鍵字是用來聲明ES6類的。
以上就是解決React報錯Style prop value must be an object的詳細內(nèi)容,更多關(guān)于React 報錯Style prop object的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
React如何實現(xiàn)Vue的watch監(jiān)聽屬性
在 Vue 中可以簡單地使用 watch 來監(jiān)聽數(shù)據(jù)的變化,還能獲取到改變前的舊值,而在 React 中是沒有 watch 的,今天通過本文給大家講解React實現(xiàn)Vue的watch監(jiān)聽屬性的方法,需要的朋友可以參考下2023-06-06詳解react、redux、react-redux之間的關(guān)系
這篇文章主要介紹了詳解react、redux、react-redux之間的關(guān)系,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04詳解如何使用React Hooks請求數(shù)據(jù)并渲染
這篇文章主要介紹了如何使用React Hooks請求數(shù)據(jù)并渲染,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10React報錯之Parameter event implicitly has a
這篇文章主要為大家介紹了React報錯之Parameter event implicitly has an any type,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08