【问题标题】:React Native: Reset children states from grandfather?React Native:从祖父那里重置子状态?
【发布时间】:2020-11-17 09:01:33
【问题描述】:

这是一个棘手的问题。假设我有一个组件<GrandFather />,里面有一个<Form /> 组件。 <Form /> 有多个 <Input /> 组件。 <Input /> 有一个内部 useState。在<GrandFather />,有一些函数,比如loadForm(加载一些字段)和unloadForm(删除这些字段)。在 unloadForm 上,我想重置输入的内部状态。我发现的唯一解决方案是在<Form /> 上有一个键并在卸载时增加它,这样就可以强制其余的。有没有更好的方法在不改变逻辑的情况下做到这一点? P.S 我正在使用 Typescript。

function GrandFather (props: Props) {
    const loadForm = () => // load some fields to the formData
    const unloadForm = () => // unload these fields to the formData

    return <Form formData={formData}/>
}

function Form (formData: FormData) {
  return (
  <>
      <Input /> // with some props
      <Input /> // with some props
      <Input /> // with some props
  </>
  )
}

function Input (props: Props) {
    const [state, setState] = useState(false);
    // the state here is being used for styling and animations, at 
    // somepoint it will became true
    return <TextInput {...props}/>
}

这里有什么方法可以将此状态重置为函数 unloadForm 上的所有输入?

【问题讨论】:

  • 可以分享一下代码吗?

标签: reactjs react-hooks state native


【解决方案1】:

我看到了两种不同的方法来实现这一点。


方法#1

作为示例,我将使用一个简单的登录表单。

因此您可以在GrandParent 上定义以下状态变量:

const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

然后,将所有usernamesetUsernamepasswordsetPassword 作为道具传递给Form,然后传递给Input 组件。

Input 组件内部,您可以通过添加以下内容将输入转换为受控输入:

<input type="text" value={username} onChange={setUsername} />

如果您需要清除输入,您可以直接从 GrandParentForm(或您可以访问设置器的任何地方)直接调用以下内容:

setUsername('');
setPassword('');

方法#2(hacky)

您可以在GrandParent 上定义一个状态变量,作为上述方法,您可以将变量和setter 作为props 传递给Form,然后传递给每个Input

const [clear, setClear] = useState(false);

然后,在Input 组件内,假设您有一个value 状态变量(使用等效的设置器setValue),您可以设置一个监听器以更改状态变量clear

useEffect(() => {
  if (clear === true) {
    setValue('');
  }
}, [clear]);

然后,当您想清除所有输入值时,您可以从任何地方调用:

setClear(true);
setTimeout(() => { // the setTimeout might not be required
  setClear(false);
}, 1);

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    相关资源
    最近更新 更多