没有JSX的条件渲染

时间:2018-12-07 10:00:09

标签: javascript reactjs

是否可以对React.createElement进行以下{{3}}的操作?

render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;

    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} />
        {button}
      </div>
    );
}

我试图这样做:

render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;

    if (isLoggedIn) {
      button = React.createElement("LogoutButton" { "onClick": this.handleLogoutClick }, null);
    } else {
      button = React.createElement("LogoutButton" { "onClick": this.handleLoginClick }, null);
    }

    return (
      React.createElement("div", null, {button});
    );
}

但是它不起作用。我该怎么办?

1 个答案:

答案 0 :(得分:0)

更改

render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;

    if (isLoggedIn) {
      button = React.createElement("LogoutButton" { "onClick": this.handleLogoutClick }, null);
    } else {
      button = React.createElement("LogoutButton" { "onClick": this.handleLoginClick }, null);
    }

    return (
      React.createElement("div", null, {button});
    );
}

render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;

    if (isLoggedIn) {
      button = React.createElement(LogoutButton, { "onClick": this.handleLogoutClick }, null);
    } else {
      button = React.createElement(LogoutButton, { "onClick": this.handleLoginClick }, null);
    }

    return (
      React.createElement("div", null, {button});
    );
}

现在您的代码应该可以正常工作了,请参阅this page以获取将来的参考