繁体   English   中英

如何让我的 url 适用于 Reactjs 中的所有按钮?

[英]how to make my url work for all my buttons in Reactjs?

我希望当我点击控制台中显示的 3 个按钮之一时,按钮的国家! 我在那里创建了此代码,但未定义国家/地区,我不知道该怎么做

例如:当我单击控制台中的<Button>France</Button>时,我希望:一个包含状态值的对象。

import React, { Component } from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from './components/Button';

class App extends Component {

  constructor() {
    super();

    this.state = {
      name: '',
      capital: "",
      flag: "",
      population: 0,
      region: "",

    }
  }

  componentDidMount(country) {
    const url = `https://restcountries.eu/rest/v2/name/${country}`;
    
    fetch(url)
      .then(res => res.json())
      .then(json =>
        this.setState({
          name: json[0].name,
          capital: json[0].capital,
          flag: json[0].flag,
          population: json[0].population,
          region: json[0].region,
        }))
      .catch(error => error);

    console.log(this.state)
  }

  render() {
    return (
      <div className="App">

        <p> name= {this.state.name}</p>
        <p> capital= {this.state.capital}</p>
        <p> flag= {this.state.flag}</p>
        <p> population= {this.state.population}</p>
        <p> region= {this.state.region}</p>

        <Button onClick={this.componentDidMount.bind(this, 'france')}>France</Button>
        <Button onClick={this.componentDidMount.bind(this, 'brazil')}>Brazil</Button>
        <Button onClick={this.componentDidMount.bind(this, 'croatia')}>Croatia</Button>
      </div>
    );
  }
}

export default App;

componentDidMountcomponentDidMount生命周期的函数。 只有在您的组件第一次正确渲染时才会调用它。 你不能在渲染函数中调用这个函数。 您需要创建一个函数并在render 方法中调用它。

class App extends React.Component {

   handleClick = (country) => {
     // do what you want.
     console.log(country)
   }

   render() {
      <button onClick={() => handleClick('france')} />
   }

}

如何让我的 URL 适用于 Reactjs 中的所有按钮?

暂无
暂无

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

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