Facebook React 根据 url 哈希渲染不同的组件

Facebook React to render different components based on url hash

本文关键字:组件 哈希渲 React 根据 url Facebook      更新时间:2023-09-26
如何

根据更改的哈希 url 渲染反应类?

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

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

有没有更简单的方法可以做到这一点,而不必添加状态值和按钮函数?
我需要使用混入吗?

你可以为此使用一个简单的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 的路由器,并使用 mixin 将它们连接到您的组件(例如控制器或主干网的路由器)。