简体   繁体   English

setState 不适用于 useState 内的 onChange

[英]setState not work by onChange inside useState

I am using useState Hook to store a form to manage view when user click.我正在使用 useState Hook 来存储表单以在用户单击时管理视图。 The interface display good but I cannot enter value in the input field.界面显示良好,但我无法在输入字段中输入值。 Can anyone tell me why?谁能告诉我为什么? thanks.谢谢。

const [url, seturl] = useState({url: ''});
const changeUrl = (field) => (event) => {
    seturl({
    ...url,
    [field]: event.target.value,
   });
 };
const [step, setStep] = useState(
   <form>
     <input type="text" value={url.url} onChange={changeUrl('url')}/>
    </form>
);
return (
  <div>{step}</div>
);

If you are passing something to the function on onChange you need to call it like:如果您将某些内容传递给onChange上的函数,则需要像这样调用它:

onChange={e => seturl({ url: e.target.value })}

Or you can simply achieve this by doing:或者您可以简单地通过执行以下操作来实现此目的:

const [url, setUrl] = useState('');

return (
  <div>
    <form>
     <input type="text" value={url} onChange={e => setUrl(e.target.value)}/>
    </form>
  </div>
);

The take away from the above example is use hooks to facilitate yourself and get rid of managing the object.从上面的例子中得出的结论是使用钩子来方便自己并摆脱管理对象。 If you have more fields like url and page , you can create multiple states like:如果您有更多字段,例如urlpage ,您可以创建多个状态,例如:

const [url, setUrl] = useState('');
const [page, setPage] = useState('');

Hope this will help you.希望这会帮助你。

You need to call the changeURL function onChange, not everytime.您需要调用changeURL函数 onChange,而不是每次都调用。

With your code, changeUrl('url') is fired on each render.使用您的代码,每次渲染都会触发 changeUrl('url')。 To avoid this, you need to call it as a function, with the event of your input field : onChange={e => changeUrl(e)}为避免这种情况,您需要将其作为函数调用,并带有输入字段的事件: onChange={e => changeUrl(e)}

 const [url, seturl] = useState("url");

  const changeUrl = event => {
    seturl( event.target.value);
  };

  return (
    <div>
      <form>
        <input type="text" value={url} onChange={(e)=>changeUrl(e)} />
        <p>URL: {url}</p>
      </form>
    </div>
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM