简体   繁体   中英

Passing onChange from parent overides onChange of the child component - React

Let's say I have an Input component with onChange event handler in it, say count input characters(just to illustrate there's a build-in functionality in that component that I want to use no matter what) and I want to use this Input like across all of my other components:

const Input = (props) => {
  const { name, value, countLimit, ...restProps } = props;
  const [count, setCount] = useState(0);

  const countCharacters = (e) => {
    setCount(e.currentTarget.value.length);
  };

  return (
    <div>
      <input
        name={name}
        value={value}
        onChange={countCharacters}
        {...restProps}
      />
      <br />
      Count: {count} / {countLimit}
    </div>
  );
};

The problem though, is that if I want to pass an onChange event handler from outside this component, say to grab some input's value or pass some data from child to parent or something else, it will override this countCharacters one. What is the best way to deal with this kind of scenarios?

Invoke props.onChange (if it exists) from within countCharacters :

const Input = (props) => {
  const { name, value, countLimit, onChange, ...restProps } = props;
  const [count, setCount] = useState(0);

  const countCharacters = (e) => {
    setCount(e.currentTarget.value.length);
    onChange?.(e);
  };

  return (
    <div>
      <input
        name={name}
        value={value}
        onChange={countCharacters}
        {...restProps}
      />
      <br />
      Count: {count} / {countLimit}
    </div>
  );
};

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