[英]React.js If Statement
我在 React 中編寫 if 語句時遇到了困難(對此有點新)
class TEST extends React.Component {
render() {
const TEST = props => {
if (props.isLoggedin("True")) {
return (
<Welcome />
);
}
return (null);
};
}
}
export default Switch(TEST);
我收到的錯誤消息是:
你的渲染方法應該有 return 語句
不確定最好的寫法? 謝謝
您不需要const TEST = props => { }
部分,除此之外看起來還可以。
嘗試如下:
class TEST extends React.Component {
render() {
if (this.props.isLoggedin("True")) {
return <Welcome />;
}
return null;
}
}
export default Switch(TEST);
甚至更短的三元運算符:
class TEST extends React.Component {
render() {
return this.props.isLoggedin("True") ? <Welcome /> : null;
}
}
我希望這有幫助!
也許你想做這樣的事情:
class TEST extends React.Component {
render() {
if (this.props.isLoggedin("True")) {
return (
<Welcome />
);
}
return (null);
}
}
或者這個(如果你想使用功能組件):
const TEST = props => {
if (props.isLoggedin("True")) {
return (
<Welcome />
);
}
return (null);
};
}
你也可以這樣做:
const TEST = props => props.isLoggedin("True") && <Welcome />
您實際上擁有的是您只在您的渲染方法中定義了一個 function ,這需要一個return
語句。
請參閱: https://reactjs.org/docs/components-and-props.html#function-and-class-components
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.