[英]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;
componentDidMount
是componentDidMount
生命周期的函數。 只有在您的組件第一次正確渲染時才會調用它。 你不能在渲染函數中調用這個函數。 您需要創建一個函數並在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.