0

在这里,如何在名为“Selected Planets”的选项卡中仅显示“ListSelected”组件,而在名为“Planets List”选项卡的选项卡中显示其余整个组件(FetchPlanets)。如何在不同的选项卡中仅呈现“ListSelected”组件,而在不同的选项卡中呈现其余的整个组件(“FetchPlanets”)?所以它不应该刷新作为道具传递的选定行星

FetchPlanets.jsx

import React from "react";
import { ListGroup, Container } from "react-bootstrap";
import "./components.css";
import ListSelected from "./ListSelected";
export default class FetchPlanets extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      planets: null,
      selectedPlanets: []
    };
  }
  async componentDidMount() {
    const url = "asdf";
    const res = await fetch(url);
    const data = await res.json();
    this.setState({ planets: data, loading: false });
    console.log(this.state.planets);
  }
  fetch = e => {
    const data = this.state.selectedPlanets;
    data.push(e.target.innerText);
    this.setState({
      selectedPlanets: data
    });
  };

  render() {
    const splanets = this.state.selectedPlanets.map(function(item) {
      return <li> {item} </li>;
    });
    return (
      <Container fluid>
        {this.state.loading || !this.state.planets ? (
          <div>Loading...</div>
        ) : (
          <ListGroup>
            {this.state.planets.map((planetnames, index) => {
              return (
                <ListGroup.Item
                  onClick={e => {
                    this.fetch(e);
                  }}
                  className="selectlg"
                >
                  {planetnames.id}
                </ListGroup.Item>
              );
            })}
          </ListGroup>
        )}

        <ListSelected selp={splanets} />
      </Container>
    );
  }
}
4

2 回答 2

1

您可以使用此示例将您的内容分成选项卡:react-tabs

这是代码:

import React, { Component } from 'react';
import { render } from 'react-dom';
import Tabs from "./Tabs";
import Tab from "./Tab";
import './style.css';

class App extends Component {

  render() {
    return (
      <Tabs>
        <Tab value="banana" header="Banana Header">
          Banana
        </Tab>
        <Tab value="apple" header="Apple Header">
          Apple
        </Tab>
      </Tabs>
    );
  }
}

render(<App />, document.getElementById('root'));

还有这个 npm 包似乎可以满足您的需求。它会更容易使用,看看:

import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import 'react-tabs/style/react-tabs.css';

export default () => (
  <Tabs>
    <TabList>
      <Tab>Title 1</Tab>
      <Tab>Title 2</Tab>
    </TabList>

    <TabPanel>
      <h2>Any content 1</h2>
    </TabPanel>
    <TabPanel>
      <h2>Any content 2</h2>
    </TabPanel>
  </Tabs>
);

[编辑]:我想我终于得到了你想做的事。因此,您需要在您的父级中获取您选择的行星,以便能够将其作为 prps 传递给您的 SelectedList 组件。您只需将列表设置为父状态,如下所示:

import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";

const App = () => {
  const [selectedPlanets, setSelectedPlanets] = React.useState([]);

  return (
    <div>
      <div className="tab-1">
        <FetchPlanets setSelectedPlanets={setSelectedPlanets} />
      </div>
      <div className="tab-2">

        <SelectedPlanets planets={selectedPlanets} />
        </div>
    </div>
  );
};

const FetchPlanets = ({ setSelectedPlanets }) => {
  const planets = ["Mars", "Uranus", "Earth", "Jupiter"];

  React.useEffect(() => {
    const selectedPlanets = [];
    planets.forEach(p => {
      if (p === "Mars" || p === "Jupiter") selectedPlanets.push(p); // Arbitrarily selected planets for the example
    });

    setSelectedPlanets(selectedPlanets);
  }, []);

  return (
    <div>
      {planets.map(p => (
      <span>{p} </span>
    ))}
    </div>
  );
};

const SelectedPlanets = ({ planets }) => (

  <div>
    {planets.map(p => (
      <span>{p} </span>
    ))}
  </div>
);

render(<App />, document.getElementById("root"));

这是stackblitz的复制品

于 2020-06-04T11:13:42.760 回答
1

您需要制作两个不同的组件来列出行星和选定的行星。 这是沙盒链接

这就是 app.js 的样子

import React from "react";
import "./styles.css";
import FetchPlanets from "./components/FetchPlanets";

import ListSelected from "./components/ListSelected";

import { Tabs, Tab } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  const [selectedPlanet, setSelectedPlanet] = React.useState([]);
  return (
    <div className="App">
      <Tabs defaultActiveKey="planet" id="uncontrolled-tab-example">
        <Tab eventKey="planet" title="Planets">
          <FetchPlanets updatePlanets={e => setSelectedPlanet([...e])} />
        </Tab>
        <Tab eventKey="list" title="Selected">
          <ListSelected selp={selectedPlanet} />
        </Tab>
      </Tabs>
    </div>
  );
}

这就是您选择的行星组件的样子

import { ListGroup } from "react-bootstrap";
import React from "react";
function ListSelected({ selp }) {
  return (
    <ListGroup>
      <ListGroup.Item>
        {selp.length > 0 &&
          selp.map((selected, index) => (
            <ListGroup.Item key={index}>{selected}</ListGroup.Item>
          ))}
      </ListGroup.Item>
    </ListGroup>
  );
}

export default ListSelected;

最后,这就是你的行星列表组件的样子

import React from "react";
import { ListGroup, Container } from "react-bootstrap";
import "./components.css";
export default class FetchPlanets extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      planets: null,
      selectedPlanets: []
    };
  }
  async componentDidMount() {
    const url = "https://assignment-machstatz.herokuapp.com/planet";
    const res = await fetch(url);
    const data = await res.json();
    this.setState({ planets: data, loading: false });
    console.log(this.state.planets);
  }
  fetch = e => {
    const data = this.state.selectedPlanets;
    if (!data.includes(e.target.innerText)) {
      data.push(e.target.innerText);
      this.setState(
        {
          selectedPlanets: data
        },
        () => {
          this.props.updatePlanets(this.state.selectedPlanets);
        }
      );
    }
  };

  render() {
    return (
      <Container fluid>
        {this.state.loading || !this.state.planets ? (
          <div>Loading...</div>
        ) : (
          <ListGroup>
            {this.state.planets.map((planetnames, index) => {
              return (
                <ListGroup.Item
                  key={index}
                  onClick={e => {
                    this.fetch(e);
                  }}
                  className="selectlg"
                >
                  {planetnames.id}
                </ListGroup.Item>
              );
            })}
          </ListGroup>
        )}
      </Container>
    );
  }
}
于 2020-06-04T16:57:01.430 回答