React: Hide a Component on a specific Route

前端 未结 4 1076
走了就别回头了
走了就别回头了 2020-12-31 05:01

New to React:

I have a

Component that I want to hide only when the user visit a specific page.

The way I des

4条回答
  •  别那么骄傲
    2020-12-31 05:37

    You can rely on state to do the re-rendering.

    If you navigate from route shouldHide then this.setState({ hide: true })

    You can wrap your

    in the render with a conditional:

    {
      !this.state.hide &&
      
    }

    Or you can use a function:

    _header = () => {
      const { hide } = this.state
      if (hide) return null
      return (
        
    ) }

    And in the render method:

    {this._header()}
    

    I haven't tried react-router, but something like this might work:

    class App extends Component {
    
      constructor(props) {
        super(props)
        this.state = {
          hide: false
        }
      }
    
      toggleHeader = () => {
        const { hide } = this.state
        this.setState({ hide: !hide  })
      }
    
      render() {
    
        const Main = () => (
          
            
             }
            />
            
            
          
        );
    
        return (
          
            
    ); } }

    And you need to manually call the function inside Art:

    this.props.hideHeader()

提交回复
热议问题