react 显示隐藏组件的方法_如何显示/隐藏ReactJS组件

Trying to learn ReactJS.. but what confuses me is the rendering of the component. Every example I've seen defines a React component class and at the end has something like:

React.renderComponent(

,

document.getElementById('comp')

);

I understand that it replaces the 'comp' element with my component.. that's great. But it seems if I load 20 components, all 20 render. However, I only want to render some and not all, but use all throughout my SPA. I am using DirectorJS router, and depending on if a user logs in or not, and/or goes to certain links, I want to only show one or so of components. I can't seem to find any info/examples/tutorials on how to dynamically manage showing or hiding react components. More so, what i'd really like to do is load partials depending on links clicked and in those partials they would use react components, so only at that time load/use the component. Is this possible..if so how might I handle this? I could live with loading 20+ components one time the first time the app is loaded, but i'd prefer to only load them if the partial a component is displayed on is loaded.

解决方案

First, render only what's necessary. It's easier to track and it's faster.

To actually "swap between pages", it's as simple as, well, setting a variable in your state/props, and use that var to conditionally render whatever you need. The role of selectively rendering whatever you want naturally goes to the parent component. Here's a working fiddle with Director: http://jsfiddle.net/L7mua/3/

Key part, in App:

render: function() {

var partial;

if (this.state.currentPage === 'home') {

partial = ;

} else if (this.state.currentPage === 'bio') {

partial = ;

} else {

// dunno, your default page

// if you don't assign anything to partial here, you'll render nothing

// (undefined). In another situation you'd use the same concept to

// toggle between show/hide, aka render something/undefined (or null)

}

return (

I am a menu that stays here

Home Bio

{partial}

);

}

Notice that beyond the HTML-looking JSX syntax, you're really just using JavaScript. Conditionals still work, iterations still work, etc.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值