Facebook React 根据 url 哈希渲染不同的组件
Facebook React to render different components based on url hash
如何
根据更改的哈希 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 将它们连接到您的组件(例如控制器或主干网的路由器)。
相关文章:
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- Steam Web API:I'我不知道该如何处理这个看起来像哈希的url来生成图像
- AngularJS:获取链接中没有哈希的查询字符串值
- 如何在Google chrome安全首选项文件中创建扩展安全哈希代码
- 如何在浏览器重新加载时保存位置哈希状态
- jQuery scrollTop-哈希错误
- 动态添加哈希标记;t工作
- 在Javascript中实现对哈希值的暴力攻击
- 如何在JavaScript/Node中计算SHA256哈希和Base64字符串编码
- 使用Javascript/jQuery以编程方式将当前锚点/哈希/片段附加到任何表单操作url
- 可以在React Native中制作一个自哈希应用程序
- 重定向不带哈希的URL-Ember.JS
- 正在测试主干事件哈希
- JavaScript对象作为哈希?复杂性是否大于O(1)
- 如何在JavaScript中实现哈希表
- 如何根据传入的哈希标签发送PHP请求
- 在我的图库(jQuery)中使用箭头导航时,更改URL中的哈希
- 哈希被推到猫鼬模型上作为'[对象对象]”;
- 哈希和数字
- Facebook React 根据 url 哈希渲染不同的组件