blog
blog copied to clipboard
React 条件渲染方法大全
使用 if else
import React from 'react'
interface Feed {
name: string
price: string
}
const FeedList: React.FunctionComponent<{ feeds: Feed[] }> = props => {
const { feeds } = props
if (feeds.length) {
return <div>have no data</div>
} else {
return (
<div>
{feeds.map(item => (
<p>
{item.name}:{item.price}
</p>
))}
</div>
)
}
}
使用 switch
const Content: React.FunctionComponent<any> = ()=> {
const [style, setStyle] = useState<number>(0)
return (
<div>
{(() => {
switch (style) {
case 1:
return 'black'
break
case 2:
return 'pink'
break
default:
return 'white'
}
})()}
</div>
)
}
使用三元运算法
const FeedList: React.FunctionComponent<{ feeds: Feed[] }> = props => {
const { feeds } = props
return (
<div>
{feeds.length
? 'have no data'
: feeds.map(item => (
<p>
{item.name}:{item.price}
</p>
))}
</div>
)
}
使用逻辑 &&
运算法
当渲染不是非一即二的时候,而只是在某一情况下渲染时,使用三元运算法就会出现 null
、undefined
、false
、空字符串之类的值,这在我看来好像有点奇怪,有点不必要
const UserInfo: React.FunctionComponent<InfoProps> = props => {
const { name } = props
return (
<div>
{ name ? <p>name</p> : null }
</div>
)
}
这个时候或许使用逻辑运算符会是更好的选择:
const UserInfo: React.FunctionComponent<InfoProps> = props => {
const { name } = props
return (
<div>
{ name && <p>name</p> }
</div>
)
}
使用枚举
我们经常使用js对象 key...value
的形式存储内容,使用 .
操作符来取的相应的值(这是一种hash表),如果我们将这个与 react component 结合就会发生奇妙的反应:
const APP: React.FunctionComponent<any> = ()=> {
const [type, setStyle] = useState<string>('noData')
return (
<div>
{
{
networkError: <div>some error with your network</div>,
noData: <div>have no data</div>,
success: <div>have data</div>
}[type]
}
</div>
)
}
可能将这个 value
为 React Component 的对象单独抽出来或许更方便理解
const APP: React.FunctionComponent<any> = ()=> {
const [type, setStyle] = useState<string>('noData')
const content = {
networkError: <div>some error with your network</div>,
noData: <div>have no data</div>,
success: <div>have data</div>
}
return (
<div>
{content[type]}
</div>
)
}
当我初次接触到这种写法的时候,最直观的感觉就是这就是 switch
的替代(alternate),这就是多种状态下的优雅编程。
但是,我很好奇,这是怎么运行的,我在命令行中编写类似的代码:
{a: 12, b:13}['a']
如我所料,这应该会报错,是一种语法错误:
那么为什么在 jsx
中却是可以正确运行,why?
我思索再三,jsx 组件会被 babel 转化为 React.createElement
这类的函数,如下:
其实本质上我们的枚举值会成为函数 React.createElement
的一个参数,那么这个参数就会运行一次拿到表达式的返回值,那么就是等于
({a: 12, b:13}['a'])
不出所料,这正常运行了,并拿到了相应的值。
这个形式非常类似于我们初学 JavaScript 时的匿名自执行函数:
我们还被告诉,如果我们不关心函数返回值,我们可以在函数表达式上前加上一元操作符同样生效,同理运用在我们这里同样生效,虽然我们这里显然需要拿到返回值,但是至少不报错了:
why?仅仅是 JavaScript 解析器解析语法的规则?原谅我不是科班出身,对编程语言底层不了解,但我对此非常感兴趣,如果有知道的同学期待您能告诉原因,或者告诉我应该学习什么来获取答案。
扯的有点远了,但是记住,枚举值是一种非常优秀的条件渲染模式。
使用高阶组件
这是一个摘自 robinwieruch
博客的例子:
// HOC declaration
function withLoadingIndicator(Component) {
return function EnhancedComponent({ isLoading, ...props }) {
if (!isLoading) {
return <Component { ...props } />;
}
return <div><p>Loading...</p></div>;
};
}
// Usage
const ListWithLoadingIndicator = withLoadingIndicator(List);
<ListWithLoadingIndicator
isLoading={props.isLoading}
list={props.list}
/>
我对于高阶组件用的不多,但是很明显的一点就是如果你封装了一个公共组件,那么这种模式很有用。
使用 do
表达式
do
表达式现在是在第一阶段,仓库在 https://github.com/tc39/proposal-do-expressions ,因此使用时需要添加相应的 babel plugin:@babel/plugin-proposal-do-expressions:
这个插件最终会将其转化为三元操作符,如下:
以上就是我使用过的条件渲染方法,希望对你有用,欢迎补充~
最后是一个广告贴,最近新开了一个分享技术的公众号,欢迎大家关注👇