绑定到局部变量的简单 show/hide 元素

Simple show/hide elements binding to local variables

一个 show/hide 元素如何基于具有 styled-components 的局部布尔变量?

我有以下内容:

export const Test = styled.div`
    width: 100px;
    height: 100px;
    background: pink;
`;

let visible = true;

function toggle() {
    visible = !visible;
}
export function App() {
    return(
        <button onClick={toggle}>toggle</button>
        <Info show={visible}>Some info</Info>
    );
}
import App from './App';

ReactDom.render(<App />, document.getElementById('root'));

Here is a stackblitz

您正在尝试在组件中引入状态,在这种情况下,您将不得不使用 class 组件而不是函数组件。

import React, { Component } from 'react'

export const Test = styled.div.attrs(props => ({
    display: props.size ? 'block' : 'none'
}))`
    width: 100px;
    height: 100px;
    background: pink;
`;

export default class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: true
        }
    }
    toggle() {
        this.setState({ visible: !this.state.visible })
    }
    render() {
        return(
            <button onClick={this.toggle}>toggle</button>
            <Info show={this.state.visible}>Some info</Info>
        );
    }
}

Function and class components React Docs.

改进完整代码

import React, { Component } from 'react';
import styled from 'styled-components';

class App extends Component {
  state={toggle:true}
   // Functions
    toggleIt=()=> {
      this.setState(prev=>({toggle:!prev.toggle}))
    } 
  render() {
    const Test = styled.div`
    width: 100px;
    height: 100px;
    background: pink;
    display: ${props => props.show ? 'block' : 'none'}
`;

    return (
      // html
      <div>
        <button onClick={this.toggleIt}>Toggle me</button>
        <Test show={this.state.toggle}>Some info</Test>
      </div>
    );
  }
}

export default styled(App) `
  width: 100vw;
  height: 100vh;
  text-align: center;
`;

供您参考 Live Demo