如何根据更改后的哈希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'
}


但它只能使用一次(即第一个网址是什么-带或不带#号标签)。

我如何才能使网址哈希更改(单击href)在点击时被拾取?
也就是说,然后单击test link,页面应显示this is a test而不是this is a sentence

有没有一种简单的方法,而不必添加状态值和按钮功能?
我需要使用mixins吗?

最佳答案

您可以为此使用简单的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()


对于更认真的项目,应使用现有的路由库。最受欢迎的是react-router。您还可以使用非特定的路由器来做出反应,并使用混合线将它们连接到您的组件(例如,导向器或骨干网的路由器)。

关于javascript - Facebook React根据URL哈希渲染不同的组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27840365/

10-09 21:53