Skip to content

Instantly share code, notes, and snippets.

@wulucxy
Last active July 9, 2018 01:12
Show Gist options
  • Save wulucxy/49ddfdef958e0afa8e88c6d7f2159c4d to your computer and use it in GitHub Desktop.
Save wulucxy/49ddfdef958e0afa8e88c6d7f2159c4d to your computer and use it in GitHub Desktop.
React IF 条件判断组件 #react
import React from 'react'
import PropTypes from 'prop-types'
class IF extends React.PureComponent {
static defaultProps = {
fallback: null
}
static propTypes = {
children: PropTypes.oneOfType([PropTypes.element, PropTypes.string])
.isRequired,
fallback: PropTypes.oneOfType([PropTypes.element, PropTypes.string]),
condition: PropTypes.bool.isRequired
}
render () {
const { children, condition, fallback } = this.props
return condition ? children : fallback
}
}
export default IF

Usage:

<IF condition={this.state.showSecret} fallback="YOU CANNOT SEE!">
  <h3>And here it is - a secret key</h3>
</IF>

Props:

name type required default description
children element, string 条件判断子元素
condition bool 条件判断语句
fallback element, string 不满足条件渲染的展示
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment