我正在将一个已经为另一个项目建立的网站移植到React中,并想为我的导航栏设置一个状态,并试图设置我的条件以首先呈现我的页面,但是它总是抛出语法错误
我尝试将{}括起来的if更改为(),以查看是否这样做。我还尝试将if包裹在{()}中,什么也没包裹
Assets/Plugins/Android/
答案 0 :(得分:2)
与括号无关,您可以尝试以下操作:
class App extends Component {
state = {
page: 0,
}
setPageChange = () => {
setState({ page: props.key })
}
renderContent() {
if (this.state.page === 1) {
return <Products />;
} else if(this.state.page === 2) {
return <Contact />;
} else {
return <Landing />;
}
}
render() {
return (
<div>
<NavBar />
{this.renderContent()}
<Footer />
</div>
);
}
}
答案 1 :(得分:0)
您应该像使用conditional rendering
{this.state.page === 1 ? <Products /> : this.state.page === 2 ? <Contact /> : <Landing />}
答案 2 :(得分:0)
另一种解决方法是:
render() {
const { page } = this.state;
return (
<div>
<NavBar />
{ (page === 1) && <Products /> }
{ (page === 2) && <Contact /> }
{ (page !== 1 && page !== 2 ) && <Landing /> }
<Footer />
</div>
);
}
答案 3 :(得分:0)
最简单的方法是这样的:
class App extends Component {
state = {
page: 0,
}
setPageChange = () => {
setState({ page: props.key })
}
render() {
const { page } = this.state;
return (
<div>
<NavBar />
{page === 1 && <Products />}
{page === 2 && <Contact />}
{page !== 1 && page !== 2 &&
<Landing />
}
<Footer />
</div>
);
}
}
答案 4 :(得分:0)
另一种方法是使用映射器对象和默认值
class App extends Component {
state = {
page: 0,
}
setPageChange = () => {
setState({ page: props.key })
}
renderContent(val) {
let obj = {
1: Products,
2: Contact,
}
return obj[val] || Landing
}
render() {
let Component = this.renderContent(this.state.page)
return (
<div>
<NavBar />
<Component />
<Footer />
</div>
);
}
}
答案 5 :(得分:0)
这是一个快速演示
function NavBar() {
return <h1>Hello Navbar</h1>;
}
function Footer() {
return <h1>Hello, Footer</h1>;
}
function Landing() {
return <h1>Hello, Landing</h1>;
}
function Contact() {
return <h1>Hello, Contact</h1>;
}
function Products() {
return <h1>Hello, Products</h1>;
}
class App extends React.Component {
state = {
page: 1,
}
setPageChange = () => {
setState({ page: props.key })
}
renderContent() {
if (this.state.page === 1) {
return <Products />;
} else if(this.state.page === 2) {
return <Contact />;
} else {
return <Landing />;
}
}
render() {
return (
<div>
<NavBar />
{this.renderContent()}
<Footer />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>