简体   繁体   English

React 包装器组件未按预期工作

[英]React wrapper component not working as expected

I am using React-Dropzone and following the first example on the website:我正在使用React-Dropzone并遵循网站上的第一个示例:

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

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

I want to create a wrapper class like this:我想像这样创建一个包装器 class :

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.但是当我这样做时, react-dropzone 停止工作。 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.这背后的原因是如果您在 MyDropzone 功能组件中定义 Wrapper,它会在您每次渲染时定义新组件。 Which means if will rerendered every render.这意味着如果将重新渲染每个渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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