React Context.Consumer中如何使用if语句实现条件渲染?
在React Context.Consumer中实现条件渲染
我来帮你搞定这个问题,其实在React的Context.Consumer里做条件判断非常直接,利用JSX本身支持的表达式特性就行,给你两种常用的实现方式:
方法1:使用三元运算符
三元运算符是最直观的条件渲染方式,适合你需要在条件不满足时可能渲染其他内容的场景(如果不需要,返回null即可,React不会渲染null)。
修改后的代码如下:
class LogInBox extends Component { render() { return( <MyContext.Consumer> {(context) => context.state.showLoginBox ? ( <div className="logInBoxWrapper" id="logInBoxId"> <div className="logInBox"> <h3>袙芯泄褌懈</h3> <form method=""> <input name="email" placeholder="协谢械泻褌褉芯薪薪邪褟 锌芯褔褌邪" required/> <input name="password" type="password" placeholder="袩邪褉芯谢褜" required/> <button type="submit">袙芯泄褌懈</button> </form> </div> </div> ) : null} </MyContext.Consumer> ); } }
方法2:使用&&短路求值
如果你的场景是条件满足时渲染弹窗,不满足时什么都不渲染,那么用&&短路求值会更简洁:
class LogInBox extends Component { render() { return( <MyContext.Consumer> {(context) => context.state.showLoginBox && ( <div className="logInBoxWrapper" id="logInBoxId"> <div className="logInBox"> <h3>袙芯泄褌懈</h3> <form method=""> <input name="email" placeholder="协谢械泻褌褉芯薪薪邪褟 锌芯褔褌邪" required/> <input name="password" type="password" placeholder="袩邪褉芯谢褜" required/> <button type="submit">袙芯泄褌懈</button> </form> </div> </div> )} </MyContext.Consumer> ); } }
原理说明
Context.Consumer的回调函数需要返回一个React元素(或者null/false/undefined这类React会忽略的值),所以我们可以直接在回调里嵌入条件判断表达式,根据context.state.showLoginBox的值决定返回弹窗组件还是空值。
内容的提问来源于stack exchange,提问作者Ivan Burzakovskyi
相关产品推荐
相关产品推荐

