reactjs - ReactJs 功能组件 - 如何从外部调用函数?
问题描述
如何从功能组件外部调用函数。
我有一个这样的功能组件
import React, { useState } from 'react';
const Hello = () => {
// call updateField() here
};
const Headline = () => {
const [greeting, setGreeting] = useState(
'Hello Function Component!'
);
// Function inside Headline, I want to call this function in Hello()
const updateField = () => {
}
return <h1>{greeting}</h1>;
};
export default Headline;
我想在 Headline() 之外的 Hello() 中调用 updateField()。请建议。
解决方案
这里有两种方法可以做到这一点,
方法一:将公共状态移动到父组件
const ParentComponentWithHelloAndHeadline = () => {
const [field, setField] = useState()
const updateField = () => { ... }
return (
<>
<Headline field={field} updateField={updateField} />
<Hello updateField={updateField} />
</>
)
}
方法 2:使用React.Context(避免道具钻探,以防使用方法 1 存在问题)
const CommonContext = React.createContext({
field: 'commonField',
updateField: () => { ... }
})
const Hello = () => {
const { field, updateField } = useContext(CommonContext)
// call updateField() here
};
const Headline = () => {
const { field, updateField } = useContext(CommonContext)
const [greeting, setGreeting] = useState(
'Hello Function Component!'
);
return <h1>{greeting}</h1>;
};
export default Headline;
function RootApp() {
return (
<CommonContext.Provider>
<Headline />
...
...
<Hello />
</CommonContext.Provider>
);
}
推荐阅读
- javascript - jquery on drop 功能不起作用
- python - Tkinter 不使用 Pycharm
- java - How does Collections.unmodifiableList (Java 8 SE) get modified when making a new ArrayList from it?
- r - 多边形内的网格点:以前的解决方案对我不起作用
- batch-file - 批处理文件 - TASKKILL /FI "WINDOW TITLE ..." 不工作
- fullcalendar - 月视图中的半角事件?
- angular - 角度:更改选择选项
- python - 当前时间等于另一个时间时如何使用函数:Python
- azure - 我们可以订阅电子邮件 ID 或单元号码作为 Azure 事件中心/通知中心的订阅者吗?
- javascript - 从 html 输入元素获取本地文件路径