我一直试图在我的应用程序中点击按钮切换两个组件。
一个是Form组件,当我点击按钮时加载精细,另一个是Table Component,它有排序部分和表本身的设计。
当我尝试在生成错误后切换到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;
我该怎么做才能切换渲染标签组件?
谢谢。
答案 0 :(得分:2)
如同在&#39;标签&#39;组件,你从道具中取出物品数组,你必须传递&#39;项目&#39;来自&#39; Main&#39;组件到&#39;标签&#39;成分
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';
const items = [
{name: 'something', origin: 'here', destination: 'there', seats: 3},
{name: 'something1', origin: 'here', destination: 'there', seats: 3},
{name: 'something2', origin: 'here', destination: 'there', seats: 3}
]
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 items={items} />
}
</div>
);
}
}
export default Main;
答案 1 :(得分:1)
在评论部分讨论之后,让我们说你有一些像
这样的项目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;