React学习之条件视图渲染(六)
来源:互联网 发布:app软件商店 编辑:程序博客网 时间:2024/06/12 00:44
1.条件化视图渲染的必要性
当你创建不同的组件的时候,可能需要通过你的应用state
的数据来显示数据
class Creeting extends React.Component{ constructor(props){ super(props); this.state = { isLoggedIn : false }; this.changeLog = this.changeLog.bind(this); } changeLog(){ console.log('-------'); this.setState((preState, props) => ({ isLoggedIn : !preState.isLoggedIn })); } render(){ if(this.state.isLoggedIn) return <h1 onClick={this.changeLog}>Welcome back!</h1>; else return <h1 onClick={this.changeLog}>Please sign up.</h1>; }}ReactDOM.render( // Try changing to isLoggedIn={true}: <Creeting />, document.getElementById('example'));
这里需要再次提醒的是,对于我们的组件是绑定事件的是没有浏览器处理的,它只是作为props
中的一个属性而存在,传递它的子元素,只有我们的DOM
标签才具有让浏览器响应它的绑定事件,也就是说<Creeting onClick={func}/>
,这个func
函数不会直接起作用。但是我们可以在这个组件内部通过props.onClick
来传递,只有用在了DOM
标签JSX
语句才会成为被浏览器处理的事件
2.逻辑运算符的运用(三元运算符的使用就不说了)
function Mailbox(props) { const unreadMessages = props.unreadMessages; return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div> );}const messages = ['React', 'Re: React', 'Re:Re: React'];ReactDOM.render( <Mailbox unreadMessages={messages} />, document.getElementById('root'));
当unreadMessages.length > 0
为true
时,就会执行后面的语句,此用法属于基本的逻辑运算规律,同样的||
在此处也可以运用。
如果有必要,可以隐藏组件输出,在render
中返回null
即可
function WarningBanner(props) { if (!props.warn) { return null; } return ( <div className="warning"> Warning! </div> );}class Page extends React.Component { constructor(props) { super(props); this.state = {showWarning: true} this.handleToggleClick = this.handleToggleClick.bind(this); } handleToggleClick() { this.setState(prevState => ({ showWarning: !prevState.showWarning })); } render() { return ( <div> <WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}> {this.state.showWarning ? 'Hide' : 'Show'} </button> </div> ); }}ReactDOM.render( <Page />, document.getElementById('root'));
下一篇博客讲的是
React
中的列表处理
1 0
- React学习之条件视图渲染(六)
- React-(if)条件渲染-condition
- react-bits:条件渲染
- react条件渲染
- React中的条件渲染
- React 条件渲染 if
- 【React全家桶入门之六】渲染用户列表
- 曹可爱之最可爱-Vue.js入门(六)条件渲染
- 小程序学习之视图与渲染
- Spring学习笔记之渲染Web视图
- react爬坑之通过条件渲染控制组件的渲染与否
- React学习(六)PropTypes
- Vue学习日志:条件渲染(6)
- 微信小程序之wx:if视图层的条件渲染 —— 微信小程序教程系列(10)
- SpringSecurity学习笔记之六:保护视图
- Vue.js 学习(6) -- Vue指令之:条件渲染
- Spring实战-读书笔记(六)-渲染Web视图
- React-数据列表渲染学习
- YUV转RBG
- 工业控制系统
- 2
- 黑苹果引导工具 Clover 配置详解及Clover Configurator使用
- 《ACM程序设计》书中题目P(会贿赂猫的胖老鼠)
- React学习之条件视图渲染(六)
- 一张图带你了解Android5.0中的colorPrimary、colorPrimaryDark、colorAccent
- 转:浅析PageRank算法
- leetcode 88. Merge Sorted Array
- 不通过setter方法改变私有变量值
- 内存管理
- NS_Binding_Aborted error for ajax function
- LintCode 字符串查找
- react-lazyload 懒加载的好处与使用