gpt4 book ai didi

javascript:当用户输入网址时实时获取并显示 youtube 缩略图

转载 作者:行者123 更新时间:2023-12-01 02:13:20 25 4
gpt4 key购买 nike

我正在使用 React 前端制作一个网络应用程序。有一个url输入框,下面是一个img显示面板。我想要做的是,当用户在输入框中键入 youtube url 时,视频的缩略图应自动显示在下面的 img 面板中。我已经制作了一个用于获取 YouTube 缩略图的函数,如下所示

fetchYouTube(event) {
const state = this.state;
state[event.target.name] = event.target.value;
this.setState(state);

function getImageThumbnail(state) {
var videoid = state.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);
if (videoid != null) {
this.setState({
ytimage: `https://img.youtube.com/vi/${videoid[1]}/0.jpg`
});
return this.state.ytimage;
} else {
return "invalid video id";
}
}
}

这是获取并显示缩略图的地方

<div className="col-md-6 no-padding">
<input type="text" name="preview_video" value={preview_video} onChange={this.handleChange} id="defaultFormSubscriptionNameEx" className="form-control" placeholder="Preview Video Url" />
<div className="Video-review">
<img src={this.state.ytimage} onChange={this.fetchYouTube.bind(this)} />
</div>
</div>

如何实现这个功能?我做错了什么?

最佳答案

试试这个代码:

import axios from 'axios'
class Hello extends React.Component {

constructor(props){
super(props)
this.state = {
ytimage: null
}
}

getVideoId(){
let tempVar = this.typedUrl
return tempVar.split("?v=")[1]
}

fetchYouTube(){
let thumbnailUrl = "https://img.youtube.com/vi/"+this.getVideoId()+"/0.jpg"
this.setState({ytimage: thumbnailUrl})


}

handleChange(e){
let typedUrl = e.target.value
this.typedUrl = e.target.value
}

render() {

return (

<div> For Demo purpose
<div className="col-md-6 no-padding">
<input type="text" name="preview_video"
onBlur ={this.fetchYouTube.bind(this)}
onChange={this.handleChange.bind(this)}
className="form-control" placeholder="Preview Video Url" />

</div>

<img src={this.state.ytimage} />

</div>
)

}
}


ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);

关于javascript:当用户输入网址时实时获取并显示 youtube 缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49610571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com