繁体   English   中英

如何在reactjs中添加路由器链接

[英]How do I add router links in reactjs

我正在关注一个教程,您可以在其中使用“星球大战” api并从api中获取数据以显示在网站上。 在本教程中,他们基本上向您显示要创建一个按钮,并且当您单击该按钮时,它会显示字符信息。 但是我希望它转到使用反应路由器显示角色详细信息的另一页。 下面是代码

import axios from 'axios';
import './App.css';
import List from './List';
class App extends Component {
  constructor(props){
    super(props);
    this.state={
      people: [],
    }
    this.getPeople=this.getPeople.bind(this);
  }
  getPeople(){
    return axios.get("https://swapi.co/api/people")
    .then((response)=>{
      console.log(response.data.results);
      this.setState({people: response.data.results})
    })
  }
  componentDidMount(){
    this.getPeople()
  }
  render(){
    const {people}=this.state;
  return (
    <div className="App">
     <List people={people}/>
    </div>
  );
}

}
export default App;

List.js

import React, {Component} from 'react';
import CharInfo from './CharInfo';

class List extends Component{
render(){

const people=this.props.people;
  return (
    <div className="">
     {
         people.map((p)=>{
             console.log(p)
             return  (
                <div key={p.url}>
                     <h1 className="char-name">{p.name}</h1>
                     <CharInfo charInfo={p}/>
                </div>
             )
         })
     }
    </div>
  );
}
}
export default List;

CharInfo.js

import React, {Component} from 'react';

class CharInfo extends Component{
    constructor(props){
        super(props);
        this.state={
            expanded: false,
        }
        this.open=this.open.bind(this);
        this.close=this.open.bind(this);
    }
    open(){
        this.setState({expanded: !this.state.expanded})
    }
    close(){
        this.setState({expanded: !this.state.expanded})
    }
    render(){
        const info=this.props.charInfo; 

        if(!this.state.expanded){
            return <p className="btn btn-info" onClick={this.open}>Show info</p>
        }
        return (
            <div className="user-details">
                <p className="btn btn-danger" onClick={this.close}>Hide Info</p>
                <ul>
                    <li>
                        <h2>Gender: {info.gender}</h2>
                    </li>
                    <li>
                    <h2>Birth Year: {info.birth_year}</h2>
                    <li><h2>Hair Color: {info.hair_color}</h2></li>
                    </li>
                </ul>
            </div>
        )
    }
}
export default CharInfo;

在此链接中,您可以在codesandbox https://codesandbox.io/s/romantic-pine-lmhvn中看到代码

您需要集成react-router-dom库,以便在React应用程序中导航到不同的“页面”。

工作的代码框: https ://codesandbox.io/s/star-wars-api-8bbuf

App.js

import React, { Component } from "react";
import axios from "axios";
import List from "./List";
import Character from "./Character";
import { BrowserRouter, Route } from "react-router-dom";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      people: []
    };
    this.getPeople = this.getPeople.bind(this);
  }
  getPeople = () => {
    axios.get("https://swapi.co/api/people").then(response => {
      this.setState({ people: response.data.results });
    });
  };
  componentWillMount() {
    this.getPeople();
  }
  render() {
    const { people } = this.state;
    console.log(people);
    return (
      <BrowserRouter>
        <Route
          path="/"
          exact
          render={props => <List {...props} people={this.state.people} />}
        />
        <Route
          path="/char/:charName"
          render={props => {
            const { charName } = props.match.params;
            const foundCharacter = this.state.people.find(
              person => person.name.split(" ").join("") == charName
            );
            return <Character {...props} info={foundCharacter} />;
          }}
        />
      </BrowserRouter>
    );
  }
}
export default App;

CharInfo.js

import React, { Component } from "react";
import { Link } from "react-router-dom";

class CharInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expanded: false
    };
    this.open = this.open.bind(this);
    this.close = this.open.bind(this);
  }
  open() {
    this.setState({ expanded: !this.state.expanded });
  }
  close() {
    this.setState({ expanded: !this.state.expanded });
  }
  render() {
    const info = this.props.charInfo.name.split(" ").join("");

    return (
      <div className="user-details">
        <Link className="btn btn-info" to={`/char/${info}`}>
          Show info
        </Link>
      </div>
    );
  }
}
export default CharInfo;

新组件: Character.js

const Character = ({ info }) => {
  return (
    <div>
      {
        <ul>
          <li>
            <h2>{info.name}</h2>
          </li>
          <li>
            <h2>Gender: {info.gender}</h2>
          </li>
          <li>
            <h2>Birth Year: {info.birth_year}</h2>
          </li>
          <li>
            <h2>Hair Color: {info.hair_color}</h2>
          </li>
          {info.vehicles.length > 0 && (
            <li>
              <h2>Vehicles:</h2>
              <ul>
                {info.vehicles.map((vehicle, index) => (
                  <li key={index}>{vehicle}</li>
                ))}
              </ul>
            </li>
          )}
        </ul>
      }
    </div>
  );
};

export default Character;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM