Child Component has many parents and parents want to access its method. How I can achieve that?

huangapple go评论54阅读模式
英文:

Child Component has many parents and parents want to access its method. How I can achieve that?

问题

我有几个筛选器,它们由两个父组件使用。两个父组件都有一个"应用"按钮,我希望当点击它时,调用每个筛选器内部的验证函数。我该怎么做?

function DateFilter() {
const [isError, setError] = useState(false);
function validation() {
// 如果不合法,显示错误消息并禁用应用按钮
setError(true);
}

return ...
}


<DesktopDialog onApply={sendBackend}> <-- 这里有应用按钮
<DateFilter onChange={setForm}>
</DesktopDialog>

<MobileFilterModal onApply={sendBackend}> <-- 这里有应用按钮
<DateFilter onChange={(v) => setForm('date', v)}>
...其他筛选器
</MobileFilterModal>


我听说可以使用`useImperativeHandle`,但是否有其他可用的选项?
英文:

I have several filters and they are used by two parents. Both parents have apply button and I want when it is clicked validation function inside each filter to be called. How I can do that?

function DateFilter() {
  const [isError, setError] = useState(false);
  function validation() {
    // if not valid show error message and apply button disabled
    setError(true);
  }

  return ...
}
&lt;DesktopDialog onApply={sendBackend}&gt; &lt;-- apply button is there
  &lt;DateFilter onChange={setForm}&gt;
&lt;/DesktopDialog&gt;

and

&lt;MobileFilterModal onApply={sendBackend}&gt; &lt;-- apply button is there
  &lt;DateFilter onChange={(v) =&gt; setForm(&#39;date&#39;, v)}&gt;
  ...other filters
&lt;/MobileFilterModal&gt;

I heard we can use useImperativeHandle but are there alternative options I can use?

答案1

得分: 1

你需要重新考虑你的组件结构。你尝试实现的方式在React中是反模式,因为数据只能单向流动。

验证应该在你的父组件中进行,DateFilter 可能只需要接收其结果。你可以将这个常见功能提取到一个钩子中,例如。

有多种方法可以做到这一点,这完全取决于你的应用程序和其架构。

英文:

You have to rethink your component structure. What you're trying to achieve is anti-pattern in React as the data can flow only one way.

The validation should happen in your parent component and DateFilter should probably just receive the result of it. You can extract this common functionality into a hook for example.

There might be multiple ways to do this, it all really depends on your application and its architecture.

答案2

得分: 1

如果你提到了很多父母。 正确的方法将是提升状态。例如,你可以使用上下文 API

类似于你的情况的用法示例:
https://dmitripavlutin.com/react-context-and-usecontext/

英文:

If you told about a lot of parents. Right way will be lifted state up. For instance you can use context api

A usage example similar to your case:
https://dmitripavlutin.com/react-context-and-usecontext/

huangapple
  • 本文由 发表于 2023年2月14日 20:14:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定