简体   繁体   中英

React wrapper component not working as expected

I am using React-Dropzone and following the first example on the website:

function MyDropzone() {
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      Hello
    </div>
  );
}

I want to create a wrapper class like this:

function MyDropzone() {
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  function Wrapper({ children }) {
    return (
      <div {...getRootProps()}>
        <input {...getInputProps()} />
        {children}
      </div>
    );
  }

  return <Wrapper>Hello</Wrapper>;
}

but when I do this, react-dropzone stops working. When I click the element, nothing happens whereas on the first example it works fine. Isn't this how wrapper components work or am I missing something?


You can do it like this.

function Wrapper({ children }) {
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      {children}
    </div>
  );
}

function MyDropzone() {
  return <Wrapper>Hello</Wrapper>;
}

The reason behind this is if you define Wrapper inside MyDropzone functional component, it will define new component everytime you render. Which means if will rerendered every render.

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