首页 > 解决方案 > 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()。请建议。

标签: reactjsreact-functional-component

解决方案


这里有两种方法可以做到这一点,

方法一:将公共状态移动到父组件

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>
  );
}

推荐阅读