I would like that when I click on one of the 3 buttons it displays in the console, the country of buttons! 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.
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. 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.
class App extends React.Component {
handleClick = (country) => {
// do what you want.
console.log(country)
}
render() {
<button onClick={() => handleClick('france')} />
}
}
如何让我的 URL 适用于 Reactjs 中的所有按钮?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.