我有以下代码,其中文本输入框接受网址,如果有效,则应创建显示区域并提供该网址的漂亮预览。
该功能可以正常工作,除了submit
之后,可以显示几秒钟,然后消失。我大概知道原因,提交后,文本区域变为空白。我该如何解决?
import React, {useState} from 'react';
import './App.css';
import Microlink from '@microlink/react';
import { String } from 'core-js';
import Card from '@material-ui/core/Card';
import TextField from '@material-ui/core/TextField';
import Button from "@material-ui/core/Button";
import { FormControl } from '@material-ui/core';
function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return !!pattern.test(str);
}
function App (){
const [myurl, setMyurl] = useState("")
const [display, setDisplay] = useState(false)
const handleChange = (event) => {
var str = validURL(myurl)
console.log(str)
str ? setDisplay(true) : setDisplay(false)
}
return (
<form onSubmit={event => handleChange(event)} >
<TextField
id="outlined-name"
label="Name"
margin="normal"
variant="outlined"
value={myurl}
onChange={e => setMyurl(e.target.value)}
/>
<Button
type="submit"
variant="contained"
>
Submit
</Button>
{display ?
<Card>
<Microlink url={myurl}/>;
</Card> : null}
</form>
)
}
export default App;
答案 0 :(得分:0)
const handleChange = (event) => {
event.preventDefault()
var str = validURL(myurl)
console.log(str)
str ? setDisplay(true) : setDisplay(false)
}
这可以解决问题,但是如果我还缺少其他内容,我会对听取意见感兴趣:
event.preventDefault()