
需求 RT,可能会有下面三种写法:
1:
function Demo() { if (b) { return <> <A /> <B /> </> } return <A /> } 2:
function Demo() { return <> <A /> {b ? <B /> : null} // or {b && <B />} </> } 3:
function Demo() { let result = [<A key="a" />]; if (b) { result.push(<B key="b" />); } return result; } 你会怎么选择?或者用什么其他的方法?以及为什么选择这样写?
1 Cbdy 2019 年 8 月 28 日 via Android {b && <B />} 官方推荐 |
2 fuermosi777 2019 年 8 月 28 日 https://reactjs.org/docs/conditional-rendering.html "it is up to you to choose an appropriate style based on what you and your team consider more readable." |
3 Mutoo 2019 年 8 月 28 日 其他的方法: <Notification message={message} /> Notification = ({message})=>{ if(!message) return null; /* render message */ } |
4 topgrd 2019 年 8 月 28 日 via iPhone b && <B /> |
5 zcdll 2019 年 8 月 28 日 via iPhone 2 中的后者,{b && <B />} |
6 ChefIsAwesome 2019 年 8 月 28 日 via Android 跟问人怎么写判断有什么区别?你写 switch,写个 map 查表,套层函数 /组件,不都行么。jsx 妙就妙在它还是 js。 |
7 forzalianjunting 2019 年 8 月 28 日 2 后 |
12 myljs OP @Cbdy 是 0 的话,是会直接打出数字 !!b 更好,但实际上三元运算符 return null 才是最正统的,因为如果不想渲染任何东西,需要 return null https://reactjs.org/docs/conditional-rendering.html#preventing-component-from-rendering 而 !! 可能会返回组件本身 or false,当然 React 也处理了 false 的情况,用起来是没问题的。 |