简体   繁体   中英

React-native - Lint error while providing a callback function as a prop to child component (JSX props should not use functions)

I've a parent-child functional component structure, where parent fetches data to be displayed and child component displays the data. I am updating parent's state from child component. I'm sending a handler function from parent to the child as a prop, which is invoking the parent's handler function. Inside the parent's handler function, I'm updating state, however, ESLint is throwing error (JSX props should not use functions). Here is what I've done so far:

Parent Component:

const [startTime, setStartTime] = useState(new Date());

const myHandler = () => {
    const tn = new Date();
    setStartTime(tn);
}
return (
    <ChildComponent myHandler={myHandler} />
);

Child Component:

interface Props {
  myHandler:(params: any) => any;
}

const someAction = useCallback(
    (studentId: Student['id']) => () => {
      navigation.push(STUDENTROUTE, { studentId });
      myHandler(studentId);
    },
    [navigation]
);

Issue is happening on the parent component where I'm passing the handler function as a prop to the child component. Error I'm getting in couple of components is:

114:7   error    JSX props should not use functions  react/jsx-no-bind

What can I do to correct this error?

Your parent component is creating myHandler every time it runs, which the linter rule says should be avoided. Create it only once, when the component first mounts, so that it passes down a static reference every time.

const myHandler = useCallback(() => {
    const tn = new Date();
    setStartTime(tn);
}, [setStartTime]);

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