无法渲染从 React App 中的 API 获取的图像
2020-07-08
90
我从 API 中获取了图像列表,但它们都没有显示在我的应用程序中,它只是点击了 alt..
<img scr={this.state.randomImg} alt="Meme"></img>
What-I-got-on-screen-after-hitting-"generete"-button-few-times.jpg
虽然如果我只是将相同的
scr
粘贴到常规 html 文件中的
img
中,它可以完美呈现
import React, { Component } from 'react';
class MemeGenerator extends Component {
constructor() {
super();
this.state = {
randomImg: "https://i.imgflip.com/1ur9b0.jpg",
question: "",
punchline: "",
allMemes: []
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.getRandomInt = this.getRandomInt.bind(this);
this.componentDidMount = this.componentDidMount.bind(this);
}
getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
componentDidMount() {
const imgFlip = "https://api.imgflip.com/get_memes";
fetch(imgFlip)
.then(response => response.json())
.then(response => {
const memes = response.data.memes;
this.setState(
{
allMemes: memes
}
)
this.setState({
randomImg: memes[this.getRandomInt(memes.length)].url
})
console.log(this.state.randomImg);
})
}
handleChange(event) {
const { name, value } = event.target;
this.setState(
{
[name]: value
}
)
}
handleSubmit(event) {
const number = this.getRandomInt(this.state.allMemes.length);
this.setState({
randomImg: this.state.allMemes[number].url
});
event.preventDefault();
console.log(this.state.randomImg);
}
render() {
return (
<main>
<form className='make-meme'>
<input type="text" name="question" value={this.state.question} onChange={this.handleChange} />
<input type="text" name="punchline" value={this.state.punchline} onChange={this.handleChange} />
<button type="submit" onClick={this.handleSubmit}>Genenerate</button>
</form>
<div className="imgWrapper">
<img scr={this.state.randomImg} alt="Meme"></img>
<h2 className="meme-text question">{this.state.question}</h2>
<h2 className="meme-text punchline">{this.state.punchline}</h2>
</div>
</main>
);
}
}
export default MemeGenerator;
我的第一个问题请不要评判
1个回答
图片的 scr 属性应为 src
例如: 您应该有
<img src={this.state.randomImg} alt="Meme"></img>
W-B
2020-07-08