简体   繁体   English

更改 styles 取决于 state

[英]Changing styles depends on state

I am trying to hide a component when the user had signed in already当用户已经登录时,我试图隐藏一个组件

const Container = styled.div`
  display: ${(props) => props.loggedIn ? 'none' : 'block'};
`

this.state {
  loggedIn: false
}

getUrl = () => {

  //conditions to determine if user already loggedIn {
    this.setState(prevState => ({
      loggedIn: !prevState.loggedIn,
   }));

}

componentDidMount() {
  this.getUrl()
}

render() {
return (
  <SomeComponent>
   <Row>
      <Col>
        <Navbar> Navbar </Navbar>
      </Col>
      <Col>
        <Container>
          <SomeStyles>
            //somestyles
          </SomeStyles>
          <Menu>
            //MenuList
          </Menu>
        </Container>
      </Col>
    <Row>
  </SomeComponent>
);
}
}

The setState is working already. setState 已经在工作了。 But the problem is when I'm trying to pass it in Styled Components, It only get the default value of the "loggedIn" state which is false.但问题是当我试图在样式化组件中传递它时,它只会获得“loggedIn”state 的默认值,这是错误的。 So it always end up getting the 'block' value for the display.所以它总是最终得到显示的“块”值。

You need to pass the loggedIn property to Container :您需要将loggedIn属性传递给Container

// Styled Container
const Container = styled.div`
  display: ${(props) => props.loggedIn ? 'none' : 'block'};
`

// Components tree
<SomeComponent>
  <Row>
    <Col>
      <Navbar> Navbar </Navbar>
    </Col>
    <Col>
      <Container loggedIn={this.state.loggedIn}>
        <SomeStyles/>
        <Menu/>
      </Container>
    </Col>
  </Row>
</SomeComponent>

I think you should use state instead of props in your style, as props is readonly and your changes is only effect the state我认为您应该使用 state 而不是您风格的道具,因为道具是只读的,您的更改只会影响 state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM