简体   繁体   中英

Calling a function from outside functional component in react

Say I have a form outside a functional component like this:

   <TextField
        onChange={handleChange('name')}
        value={values.name}
        variant="outlined"
        label="Name"
        id="name"
        required
    />

And I have my component this way:

   export default function App() {
        const handleChange = (prop) => (event) => {
           setValues({ ...values, [prop]: event.target.value });
        };
   }

How do I call the handleChange() function from inside my component?

You could pass in the handleChange function as a prop to your functional component:

const MyComp = (props) => {
    ...
    return <TextField
        onChange={props.handleChange('name')}
        value={values.name}
        variant="outlined"
        label="Name"
        id="name"
        required
    />
}
// Reference function here.
<MyComp handleChange={handleChange}/>

if you've a form component as a child component of a component, then you can do something like so:-

  • ParentComponent.js :-
import ChildComponent from './ChildComponent

export default function ParentComponent() {
  const handleChange = (prop) => (event) => {
    setValues({ ...values, [prop]: event.target.value })
  }

  return (
    <ChildComponent 
      handleChange={handleChange} 
    />
  )
}
  • ChildComponent.js :-
export default function ChildComponent({handleChange}) {
  return (
    <TextField
      onChange={handleChange('name')}
      value={values.name}
      variant="outlined"
      label="Name"
      id="name"
      required
    />
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM