React TypeScript:使用useRef设置输入的初始值

时间:2019-11-08 06:57:02

标签: reactjs typescript

输入字段显示保存在本地存储中的值,但是我无法在输入字段中编辑该值,也不知道为什么。

我不想使用占位符,因为我希望能够编辑值。

import React, { useRef, useState } from 'react';

const ProfileComponent: React.FC = () => {
    let email = useRef<HTMLInputElement>(null);

     const saveEmail = () => {
        localStorage.setItem('email', email)
     }

  // tslint:disable-next-line: no-any
  const update = (event: any) => {
    if (event.target.name === 'email') {
      setState({ ...state, email: event.target.value });
    } else if (event.target.name === 'fullName') {
      setState({ ...state, fullName: event.target.value });
    }
  };

    interface StateInterface {
        email: string;
    }
    const [state, setState] = useState<StateInterface>({
        email: localStorage.getItem('email') || '',
    });

    return (
        <input type='text' name='fullName' ref={fullName} onChange={update} value={state.fullName} />
        <input type='text' name='email' ref={email} onChange={update} value={state.email} />
        <button onClick={saveEmail}></button>
    )

}

2 个答案:

答案 0 :(得分:1)

您提供的代码存在一些问题

1)您应该用React Fragments<> </>)包装DOM元素

2)您可能想要使用any,而不是将事件类型设置为React.FormEvent<HTMLInputElement>

3)您应该使用localStorage.setItem('email', state.email)而不是localStorage.setItem('email', email),因为email是状态对象的一部分,因此,您必须引用它才能访问值。

以下是完整的更改:

interface StateInterface {
  email: string;
  fullName: string;
}

const ProfileComponent: React.FC = () => {
  let email = useRef<HTMLInputElement>(null);
  let fullName = useRef<HTMLInputElement>(null);
  const [state, setState] = useState<StateInterface>({
    email: 'aa@gmail.com' || '',
    fullName: 'aa' || '',
  });

  const saveEmail = () => {
    localStorage.setItem('email', state.email)
    console.log(state);
  }

  const update = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.name === 'email') {
      setState({ ...state, email: event.target.value });
    } else if (event.target.name === 'fullName') {
      setState({ ...state, fullName: event.target.value });
    }
  };



  return <>
    <input type='text' name='fullName' ref={fullName} onChange={update} value={state.fullName} />
    <input type='text' name='email' ref={email} onChange={update} value={state.email} />
    <button onClick={saveEmail}>save</button>
  </>

}

答案 1 :(得分:0)

您的输入中必须有一个onChange

return (
   <input type='text' name='email' ref={email} onChange={e => setState({email: e.target.value})} 
       value= {state.email} />
     <button onClick={saveEmail}></button>
  )