iT邦幫忙

2021 iThome 鐵人賽

DAY 6
0
Modern Web

以 React 為主的那些前端事系列 第 6

Day 06 - 那些~幫助開發的套件

如果有錯誤,歡迎留言指教~ Q_Q

classnames: 可以依照邏輯條件的將 className 動態是否顯示

classnames() 可以傳入N個 string 或 object,根據 component 的 state 或是 props 來改變狀態,就可以串成想要顯示的 className 們

基本用法

// 可以傳入 string 或是 object
classNames('foo', { bar: true }); 
// => 'foo bar'

// 可以傳入 array
// object 的 value 如果是 falsy 值,則不會顯示
let arr = ['b', { c: true, d: false }];
classNames('a', arr); 
// => 'a b c'

// 也可以組合模板文字
let buttonType = 'primary';
classNames({ [`btn-${buttonType}`]: true });
// => 'btn-primary'

範例

import cx from 'classnames';

const App = ({ children }) => {
    const [isShowArrow, setIsShowArrow] = useState(false);

    return (
        <div className={cx('arrow', { 'is-show': isShowArrow })}
          {children}
        </div>
      );
}
import cx from 'classnames';

const App = ({ children }) => {
    const leftArrowClass = cx(
        'left-arrow',
        { hidden: !hasLeftArrow }
    );

    return (
        <div className={leftArrowClass}
          {children}
        </div>
      );
}

如果使用 css-modules,則將其 bind 使用

import classnames from 'classnames/bind';
import { tabHeaderStyle } from './Tab.style';

const cx = classnames.bind(tabHeaderStyle);

const App = ({ name }) => {
    return (
        <a className={cx('tab', {'isActive': true })}>
            {name}
        </a>
    );
}

idx: 幫助更方便的遍歷 object 和 array 的屬性

幫你簡化需要判斷過程中的值是否存在,如果中間屬性為 null 或未定義,則 return

import idx from 'idx';

const news = idx(data, _ => _.data.items) || {};

const quotes: IAdAndNewProps[] = idx(data, _ => _.data.items.data);


上一篇
Day 05 - TypeScript 語法
下一篇
Day 07 - 非同步流程控制
系列文
以 React 為主的那些前端事30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言