可以通過直接設定classname prop來確定類名以確定樣式,或者通過style prop來設定行內樣式。 需要注意的是,style prop需要是乙個物件。
栗子:
const style = )`,
//注意如下寫法,會自動轉換為-webkit-transition
webkittransition: 'all',
// ms是唯一小寫的瀏覽器字首
mstransition: 'all',
};const component = ;
樣式中的畫素值
當設定width和height時,可以不必新增px單位,react會自動新增:
// 渲染為height: 10px
const style = ;
reactdom.render(style=>hellocomponent>, mountnode);
使用classnames庫
**對比:
未使用:
class
button
extends
component else
if (this.state.ishovered)
return
; }
};
使用:
import classnames from 'classnames';
class
button
extends
component );
return
; }
});
css modules依舊使用css,但是使用js來管理樣式依賴。
使用css可能遇到的問題:
1、全域性汙染結合webpack的css-loader,就可以在css中定義樣式,在js檔案中匯入。2、命名混亂
3、依賴管理不徹底
4、js與css無法共享變數
5、**壓縮不徹底
栗子:
css檔案:
/* components/button.css */
.normal
.disabled
js檔案:
/* components/button.js */
import styles from './button.css';
console.log(styles);
// =>
// object
buttonelem.outerhtml = `class=$>submit`
最終生成的html:
class="button--normal-abc5436"> processing... button>
類名button–normal-abc5436是css按照localidentname自動生成的class名稱。經過這樣的混淆處理後,class的名稱基本就是唯一的。
css modules對css中的class名都做了處理,使用物件來儲存原class和混淆後的class的對應關係。
使用composes來組合樣式
對於樣式服用,cssmodules只提供了唯一的方式來處理:composes組合。
/* components/button.css */
.base
.normal
import styles from './button.css';
buttonelem.outerhtml = `class=$>submit`
生成的html:
class="button--base-abc53 button--normal-abc53"> processing... button>
class命名技巧
栗子:dialog__confirm-button--highlight
乙個結合react的栗子:
/* dialog.css */
.root {}
.confirm {}
.disabledconfirm {}
/* dialog.js */
import react, from 'react';
import classnames from 'classnames';
import styles from './dialog.css';
class
dialog
extends
component );
return (
confirm
...
); }
}
react事件處理及動態樣式新增
多資料的事件繫結,迴圈資料來進行繫結。如下方式就是迴圈繫結事件的基本 this.state.lists.map function value,index,array bind this 這裡是一塊事件繫結的例子,可以點選按鈕,點選的那個按鈕來實現選中的狀態,並且可獲取點選按鈕的值 var ask r...
react 樣式 事件
react元件 新增樣式和事件 樣式 1 元件內class屬性變成classname 其中 寫法為 classname xx 動態新增多個類 classname classname classname classname 類名 動態新增類名 classname classname 必須新增小括號,否...
React中設定樣式
div 在react中設定class時使用classname,然後引入對用的css檔案 div 方便我們在react中使用classname,可以想vue一樣進行動態的型別設定 styled components 官網 vscode.外掛程式 vscode styled components 簡單的...