【问题标题】:Facebook React to render different components based on url hashFacebook React 根据 url hash 渲染不同的组件
【发布时间】:2015-03-06 13:57:49
【问题描述】:

如何根据更改后的 hash url 渲染 react 类?

这就是我的反应代码现在的样子:

module.exports = React.createClass {   render: () ->
    div {},
      div {},
        a { href: '#testhash' }, 'test link'
      div {},
        if (window.location.hash.substring(1) is 'testhash')
          'this is a test'
        else
          'this is a sentence'
}

但它只能工作一次(即第一个网址是什么 - 有或没有主题标签)。

我怎样才能使 URL 哈希更改(单击 href)在单击时被拾取?
也就是说,然后test link被点击,页面应该是this is a test而不是this is a sentence

有没有更简单的方法来做到这一点而无需添加状态值和按钮功能?
我需要使用 mixins 吗?

【问题讨论】:

    标签: javascript coffeescript reactjs


    【解决方案1】:

    您可以为此使用简单的 mixin。 mixin 在内部使用状态和事件侦听器,但是这不会暴露给您的组件。你的组件只知道两个公共方法:

    • this.getHash()String
    • this.isHash(String)Boolean
    React.createClass {
      mixins: [HashMixin()]
      render: () ->
        div {},
          div {},
            a { href: '#testhash' }, 'test link'
          div {},
            if @isHash 'testhash'
              'this is a test'
            else
              'this is a sentence'
    }
    
    # provides getHash() to get the current hash
    # provides isHash(hash) to test for equality with a hash
    HashMixin = () ->
      getState = () -> {__hash: window.location.hash.slice(1)}
    
      getHash: () -> @state.__hash
      isHash: (hash) -> @state.__hash is hash
      getInitialState: getState
    
      componentDidMount: () -> 
        window.addEventListener 'hashchange', @__update_hash_state, false
      componentWillUnmount: () -> 
        window.removeEventListener 'hashchange', @__update_hash_state, false
    
      __update_hash_state: () -> @setState getState()
    

    对于更严肃的项目,您应该使用现有的路由库。最流行的反应是反应路由器。您还可以使用不特定的路由器进行响应,并使用 mixin 将它们连接到您的组件(例如,director 或主干的路由器)。

    【讨论】:

      猜你喜欢
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多