React Context API中的“If”语句

时间:2018-05-09 10:49:00

标签: reactjs react-context

如何在Context.Consumer中使用“if”语句?我需要检查 context.state.showLoginBox 是否为true,然后显示下面的div。

class LogInBox extends Component {
    render() {
        return(
            <MyContext.Consumer>
                {(context) => (// context.state.showLoginBox ? => show div below
                    <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>
        );
    }
}

1 个答案:

答案 0 :(得分:1)

如果使用显式返回(如

),则可以在上下文回调中使用if statement
class LogInBox extends Component {
    render() {
        return(
            <MyContext.Consumer>
                {(context) => {

               if(context.state.showLoginBox)  {
                   return <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>
                  }
                  return null;
                }}
            </MyContext.Consumer>
        );
    }
}

否则使用隐式返回,您可以使用三元运算符

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> : null
    }
}