0

如何在 Context.Consumer 中使用“if”语句?我需要检查context.state.showLoginBox是否为真,然后显示下面的 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>
        );
    }
}
4

1 回答 1

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
    }
}
于 2018-05-09T11:03:17.160 回答