The main problem I can see is that you don't pass event
argument from onClick
to your validation function, hence preventDefault()
function is not working.(我可以看到的主要问题是您没有将event
参数从onClick
传递到验证函数,因此preventDefault()
函数无法正常工作。)
Try to pass event
argument to validation function and then use this argument in function to apply preventDefault()
.(尝试将event
参数传递给验证函数,然后在函数中使用此参数以应用preventDefault()
。)
--Update--(-更新-)
You don't need to use preventDefault()
at all.(您根本不需要使用preventDefault()
。) Just modify your validation function to call new joke only if validation is passed.(只需将验证功能修改为仅在通过验证后才发出新笑话。)
import React, { useState } from "react";
function Search() {
const [joke, setJoke] = useState()
const [firstname, setFN] = useState("sharoze")
const [lastname, setLN] = useState("khan")
const newJoke = (first, last) => {
fetch(`http://api.icndb.com/jokes/random?firstName=${first}&lastName=${last}`)
.then(result => result.json())
.then(result2 => {
console.log(result2)
setJoke(result2.value.joke)
})
}
function validateForm() {
var firstname = document.getElementsByName("firstname")[0].value;
var lastname = document.getElementsByName("lastname")[0].value;
if (firstname === "" && lastname === "") {
alert("Please enter atleast one name");
return false;
}
else if (!(/^[a-zA-Z]+$/.test(firstname + lastname))) {
alert("'Only alphabets allowed'");
return false;
}
newJoke(firstname, lastname);
}
return (
<div className="jokeForm" >
<form name="searchForm" >
<input type="text" name="firstname" placeholder="First name" value={firstname} onChange={(e) => setFN(e.target.value)} />
<input type="text" name="lastname" placeholder="Last name" value={lastname} onChange={(e) => setLN(e.target.value)} />
</form>
<button id="button" onClick={() => validateForm()}>click here for a personalised chuckle</button>
<h3>{joke}</h3>
</div >
)
}
export default Search;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…