是否可以对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});
);
}
但是它不起作用。我该怎么办?
答案 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以获取将来的参考