英文:
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 ...
}
<DesktopDialog onApply={sendBackend}> <-- apply button is there
<DateFilter onChange={setForm}>
</DesktopDialog>
and
<MobileFilterModal onApply={sendBackend}> <-- apply button is there
<DateFilter onChange={(v) => setForm('date', v)}>
...other filters
</MobileFilterModal>
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/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论