我一直在尝试在应用程序中单击按钮时切换两个组件。
一个是Form组件,单击该按钮后可以很好地加载它,另一个是Table组件,它具有排序部分和表本身的设计。
当我尝试切换到表组件时,会生成以下错误:
我的切换组件是这样的:
import React, { Component } from "react";
import {
Route,
NavLink,
HashRouter
} from "react-router-dom";
import Home from "./Home";
import Stuff from "./Stuff";
import Caro from "./Carousel";
import { Carousel } from 'react-bootstrap';
import Tab from './Table';
import Form from './Form';
class Main extends Component {
state = { showing: true };
render() {
const { showing } = this.state;
return (
<div>
<button onClick={() => this.setState({ showing: !showing })}>toggle</button>
{ showing
? <Form / >
: <Tab />
}
</div>
);
}
}
export default Main;
我的表组件是这样的:
import React, { Component } from 'react';
import { Table } from 'reactstrap';
class Tab extends React.Component {
render() {
const items = this.props.items;
items.sort((a,b) => {
const name1 = a.name.toLowerCase(), name2 = b.name.toLowerCase();
return name1 === name2 ? 0 : name1 < name2 ? -1 : 1;
});
return (
<Table striped>
<thead>
<tr>
<th >Name</th>
<th>Origin</th>
<th>Destination</th>
<th>Seats</th>
</tr>
</thead>
<tbody>
{items.map(item => {
return (
<tr>
<td>{item.name}</td>
<td>{item.origin}</td>
<td>{item.destination}</td>
<td>{item.seats}</td>
</tr>
);
})}
</tbody>
</Table>
);
}
}
export default Tab;
我应该怎么做才能使切换显示选项卡组件?
谢谢。
最佳答案
在评论部分的讨论之后,假设您有一些项目,例如
const items = [{name: 'a'},{name: 'b'},{name: 'c'} ]
然后在主文件中尝试此代码
import React, { Component } from "react";
import {
Route,
NavLink,
HashRouter
} from "react-router-dom";
import Home from "./Home";
import Stuff from "./Stuff";
import Caro from "./Carousel";
import { Carousel } from 'react-bootstrap';
import Tab from './Table';
import Form from './Form';
class Main extends Component {
state = { showing: true };
render() {
const { showing } = this.state;
const items = [{name: 'a'},{name: 'b'},{name: 'c'} ]
return (
<div>
<button onClick={() => this.setState({ showing: !showing })}>toggle</button>
{ showing
? <Form / >
: <Tab items={items}/>
}
</div>
);
}
}
export default Main;
关于javascript - 在React中切换组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50597701/