css - 为什么我的 React 组件的 CSS 没有动态更新?

标签 css reactjs webpack sass material-ui

我将 redux 添加到 create-react-app 并且我一直在尝试让导航器工作。我通过突出显示事件的“页面链接”来做到这一点。我为此使用的代码是 react Hook (使用状态来记住当前页面)和 npm 包 classNames 的组合。

classNames(object['key'] && classes.activeItem)

所以这里我让 object['key'] 在特定元素被激活时评估为 true,以便该元素获得 activeItem 类。

当我用 true 替换 object['key'] 时,它起作用了。当我点击它后 console.log object['key'] 时,它的计算结果也为真。

为什么这不起作用?谢谢!

import React, { useEffect, memo } from 'react';
import { bindActionCreators, compose } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from '@material-ui/core/styles';
import { loadPage } from './actions';
import { uploadFile } from '../uploadFile/actions';
import _ from 'lodash';


const styles = theme => ({
  item: {
    paddingTop: 4,
    paddingBottom: 4,
    color: 'rgba(255, 255, 255, 0.7)',
    '&:hover': {
      backgroundColor: 'rgba(255, 255, 255, 0.08)',
    },
  },
  itemPrimary: {
    color: 'inherit',
    fontSize: theme.typography.fontSize,
    '&$textDense': {
      fontSize: theme.typography.fontSize,
    },
  },
  itemActiveItem: {
    color: '#4fc3f7',
  },
  textDense: {}
});

function Navigator(props) {
  const { classes, curPage, onUploadFile, onPageChange, dispatch, ...other } = props;

  let activePage = {
    'invite': false,
  }

  useEffect(() => {
    if(!curPage){
      onPageChange('search');
    }
    activePage = _.mapValues(activePage, () => false);
    activePage[curPage] = true
  });


  return (
    <Drawer variant="permanent" {...other}>
      <List disablePadding>
        <ListItem button className={classNames(classes.logo)}>
          <img src={require("assets/img/logo.png")} alt={''}/>
        </ListItem>

        <ListItem className={classes.categoryHeader} >
          <ListItemText classes={{ primary: classes.categoryHeaderPrimary }}>
            Files
          </ListItemText>
        </ListItem>

        <ListItem
          button
          dense
          className={classNames(classes.item, activePage['invite'] && classes.itemActiveItem)}
          onClick={() => {onPageChange('invite')}}
          >
          <ListItemIcon><PeopleIcon /></ListItemIcon>
          <ListItemText classes={{ primary: classes.itemPrimary, textDense: classes.textDense }}>
            Invite To Your Team
          </ListItemText>
        </ListItem>

      </List>

    </Drawer>
  );
}

Navigator.propTypes = {
  classes: PropTypes.object.isRequired,
  onPageChange: PropTypes.func.isRequired,
  onUploadFile: PropTypes.func.isRequired
};

const mapStateToProps = (state) => {
  const { curPage } = state.app;
  return { curPage };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onPageChange: bindActionCreators(loadPage, dispatch),
    onUploadFile: bindActionCreators(uploadFile, dispatch),
    dispatch
  };
};

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps
);


export default compose(withConnect, memo, withStyles(styles))(Navigator);

最佳答案

请注意,传递给 useEffect Hook 的函数始终在渲染之后运行。

您的 useEffect 不会导致组件重新呈现以查看更改。仅更改状态会导致重新渲染。如果你想重新渲染,你需要先使用 useState 钩子(Hook),然后你需要从 useEffect 钩子(Hook)中 setState 。或者,您可以将这两行作为渲染的一部分运行(将它们从 useEffect Hook 中移除,将它们放在外面):

activePage = _.mapValues(activePage, () => false);
activePage[curPage] = true
useEffect(() => {
    if(!curPage){
      onPageChange('search');
    }
});

但是当我查看您的代码时,我认为您可以使用 curPage === 'invite' && classes.itemActiveItem 而不是 activePage['invite'] && classes .itemActiveItem 并删除与 activePage 对象相关的那些不必要的行。这会让事情变得容易得多。

关于css - 为什么我的 React 组件的 CSS 没有动态更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56502056/

相关文章:

javascript - 边框颜色悬停效果问题

html - 在 Chrome 中编辑 CSS 规则时不要突出显示 HTML 区域

reactjs - react 使用历史: Hooks can only be called inside the body of a function component

reactjs - React Route 不适用于嵌套 URL

node.js - Webpack 捆绑 ENOENT : no such file or directory fs. readdirSync

javascript - Bootstrap 导航选项卡未突出显示事件选项卡

javascript - Protocol.end 处出现错误 : Connection lost: The server closed the connection.

javascript - 调用 firebase.auth 是否算作 firebase 限制的下载?

vue.js - npm runserve 和 npm run build 的不同 vue.config.js

html - CSS3 中的分割高度