javascript - onClick 事件触发后提交的属性不会更新

标签 javascript reactjs styled-components

我认为我的Styled Component onClick event 时不会更新被解雇了。

将变量静态设置为 true 确实显示了它应该显示的内容。 我尝试console.log()我正在更新的变量,它正在按照我的预期工作。

  • 路过collapsedMenuIsActive<StyledNavBarList>
  • toggleCollapsedMenu将从 false 切换至true<StyledNavBarBurger> 时则相反被点击

这是通过 onClick 事件切换变量的位置。

let collapsedMenuIsActive = false;

const toggleCollapsedMenu = () => {
    collapsedMenuIsActive = (!collapsedMenuIsActive);
}

{/* I have tried both of these two lines below here */}
{/* <StyledNavBarBurger onClick={toggleCollapsedMenu}> */}
<StyledNavBarBurger onClick={() => toggleCollapsedMenu}>
    ...
</StyledNavBarBurger>
<StyledNavBarList isActive={collapsedMenuIsActive}>
    ...
</StyledNavBarList>

这是我的样式组件。

export const StyledNavBarList = styled.ul`
    ...

    ${MEDIA.smallPhone`
        display: ${props => props.isActive ? 'block' : 'none'};
        ...
    `}
`;

我预计当 onClick 事件被触发时,我正在更新的变量将更新 props.isActive我里面的值(value)styled component .

最佳答案

如果您想触发 React 基于变量重新渲染,您应该使用 setState 并将 collapsedMenuIsActive 存储在状态对象中。类似下面的内容应该可以工作,但请注意,如果没有完整的代码,它可能不准确:

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            collapsedMenuIsActive: false
        };
    }

    toggleCollapsedMenu = () => {
        // This will update the state in your state object
        // and instruct React to re-render this component with the new state.
        // It's important that you use the function form of setState when
        // changing the state based on current/previous state values.
        this.setState(state => ({
            collapsedMenuIsActive: !state.collapsedMenuIsActive
        }));
    }

    render() {
        return (
            <React.Fragment>
                <StyledNavBarBurger onClick={this.toggleCollapsedMenu}>
                    ...
                </StyledNavBarBurger>
                <StyledNavBarList isActive={this.state.collapsedMenuIsActive}>
                    ...
                </StyledNavBarList>
            </React.Fragment>
        );
    }
}

要了解有关 React 状态的更多信息,请阅读 official docs 。请注意,React.Fragment 对于状态来说不是必需的,这里使用它来简单地将两个组件包装在渲染中以帮助完成此特定示例。它也可以只是一个 div 或被其他一些节点/元素包裹。

关于javascript - onClick 事件触发后提交的属性不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54506827/

相关文章:

javascript - 创建全局sql函数

reactjs - 使用样式化组件覆盖 react 组件样式

reactjs - 在 React 中使用 use state hook 合并两个数组

javascript - React-native 无法在导入 js 文件时解析模块

css - 将 CSS 文件导入到 head 中的 React 应用程序

reactjs - React 样式组件条件三元运算符

reactjs - "Missing return type on function"样式组件插值函数错误

javascript - 如何更改订阅函数内部可观察值的值?

javascript - ng-include 不加载指定文件的内容

javascript - 在调用它的函数的回调中使用参数