首页 > 解决方案 > 禁止传播道具 - React Dropzone

问题描述

在其中一个项目中,我为此解决方案使用拖放操作,我选择 React Dropzone 库。该组件工作正常,但在构建项目时出现警告warning Prop spreading is forbidden react / jsx-props-no-spreading。如何解决错误?

上传文件

const dropzoneRef = createRef();
const openDialog = () => {
  if (dropzoneRef.current) {
    dropzoneRef.current.open()
  }
};

<Dropzone ref={dropzoneRef} noClick noKeyboard>
  {({getRootProps, getInputProps, acceptedFiles}) => {
    return (
      <div className="container">
        <div {...getRootProps({className: 'dropzone'})}>
          <input {...getInputProps()} /> //Prop spreading is forbidden
          <p>Drag 'n' drop some files here</p>
          <button
            type="button"
            onClick={openDialog}
          >
            Open File Dialog
          </button>
        </div>
        <aside>
          <h4>Files</h4>
          <ul>
            {acceptedFiles.map(file => (
              <li key={file.path}>
                {file.path} - {file.size} bytes
              </li>
            ))}
          </ul>
        </aside>
      </div>
    );
  }}
</Dropzone>

文档

标签: reactjsreact-dropzone

解决方案


这是一个eslint规则,旨在为作为道具传递的内容创建更多透明度。您最终可以禁用任何 eslint 规则。由您和您的团队决定是否应关闭给定规则。如果是这种情况,您可以转到您的eslint文件并在rulesinclude "react/jsx-props-no-spreading": off

现在,如果你想加强这个规则,你需要准确地指定传递的道具,而不是像这样传播:

const dropzoneRef = createRef();
const openDialog = () => {
  if (dropzoneRef.current) {
    dropzoneRef.current.open()
  }
};

<Dropzone ref={dropzoneRef} noClick noKeyboard>
  {({getRootProps, getInputProps, acceptedFiles}) => {
    const divProps = getRootProps({className: 'dropzone'})
    const inputProps = getInputProps()
    // you could destructure instead, if the keys you extract don't collide.
    // if they do collide (like className) and you want to destructure you would need to rename same key names like:
    // const { first: inputFirst, second: inputSecond } = getInputProps()

    return (
      <div className="container">
        <div propFirst={ divProps.first } propSecond={ divProps.second } >
          <input propFirst={ inputProps.first } propSecond={ inputProps.second } />
          <p>Drag 'n' drop some files here</p>
          <button
            type="button"
            onClick={openDialog}
          >
            Open File Dialog
          </button>
        </div>
        <aside>
          <h4>Files</h4>
          <ul>
            {acceptedFiles.map(file => (
              <li key={file.path}>
                {file.path} - {file.size} bytes
              </li>
            ))}
          </ul>
        </aside>
      </div>
    );
  }}
</Dropzone>

推荐阅读