[英]React useState: How can I update my useState with onChange for input and OnClick for the button?
I am trying to update the useState hook but the object is returning empty.我正在尝试更新 useState 挂钩,但 object 返回为空。 I have tried to use something like: <input onChange={e => setFilter(name: e.target.value)} >
however, it submits on each key stroke and the button is pointless, and the user cant fully complete the value (Copy and paste only works).我曾尝试使用类似: <input onChange={e => setFilter(name: e.target.value)} >
但是,它在每次击键时提交,并且按钮毫无意义,用户无法完全完成该值(仅复制和粘贴有效)。 What am I doing wrong?我究竟做错了什么?
export default function Search() {
const [filter, setFilter] = useState({ name: "Hungary" });
const { data, loading, error } = useQuery(GET_COUNTRY_INFO, {
variables: { filter },
});
if (loading) {
return <Loader />;
}
if (error) return <p>Error</p>;
const userReq = {
name: ''
}
function onChangeHandler (e) {
const userReq = {name: e.target.value}
return userReq
};
const onClickHandler = (e) => {
setFilter(userReq)
}
return (
<div className="body">
<h1>
Get Information
<br /> about Countries!
</h1>
<div className="wrapper">
<input
className="search"
type="text"
id="search"
placeholder="Enter a Country"
onChange={onChangeHandler}
/>
<button className="submit" name="name" type="submit" onClick={onClickHandler}>
Search
</button>
{data?.Country?.[0] && <CountryInfo country={data?.Country[0]} />}
</div>
</div>
);
}
your setFilter is wrong, you are using:您的 setFilter 错误,您正在使用:
setFilter(name: e.target.value)
and should be:应该是:
setFilter({ name: e.target.value });
So, the code below should work and you dont need the 'userReq'
variable:因此,下面的代码应该可以工作,并且您不需要'userReq'
变量:
function onChangeHandler(e) {
setFilter({ name: e.target.value });
}
const onClickHandler = (e) => {
console.log(filter);
};
<input type="text" id="search" onChange={onChangeHandler} />
If you want onChange inline:如果你想要 onChange 内联:
onChange={(e) => setFilter({ name: e.target.value })}
You probably want 2 separate states here,你可能想要两个不同的状态,
A state which holds the current filter A state 包含当前过滤器
A state which holds the current user's input一个 state 保存当前用户的输入
and on clicking the button you want to sync the user's input with the filter并单击您想要将用户输入与过滤器同步的按钮
Looking at your code I think you've already figured this out, so just making your userReq
a state should solve your problem查看您的代码,我认为您已经弄清楚了,因此只需将您的userReq
state 即可解决您的问题
Basically changing this基本上改变这个
const userReq = {
name: ''
}
function onChangeHandler (e) {
const userReq = {name: e.target.value}
return userReq
};
to this对此
const [userReq, setUserReq] = useState({ name: '' })
function onChangeHandler (e) {
setUserReq({ name: e.target.value })
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.