简体   繁体   English

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

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

I would like that when I click on one of the 3 buttons it displays in the console, the country of buttons!我希望当我点击控制台中显示的 3 个按钮之一时,按钮的国家! I created this code there but the country is not defined, I don't know how to do it我在那里创建了此代码,但未定义国家/地区,我不知道该怎么做

For example : I would like that when I click on the <Button>France</Button> in the console: an object where there are the values ​​of state.例如:当我单击控制台中的<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;

the componentDidMount is a function of the lifecycle of your component. componentDidMountcomponentDidMount生命周期的函数。 It is called only when your component is rendered for the first time correctly.只有在您的组件第一次正确渲染时才会调用它。 You can't call this function in the render function.你不能在渲染函数中调用这个函数。 You need to create a function and call it in the render method.您需要创建一个函数并在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