首页 > 解决方案 > 在反应组件中设置状态而不是类

问题描述

我正在开发一个拖放组件 - 但我不确定您将如何在 const 导出类型的组件中设置状态?我应该把它变成一个类 - 如果是这样的话,这些属性的后果是什么?

我想编辑组件-因此拖放将注册为文件上传-以编程方式上传文件-用户刚刚拖放到组件中。

import React from "react";
import TextField from "@material-ui/core/TextField";
import FormControl from "@material-ui/core/FormControl";

const renderDragDrop = ({
  input,
  rows,
  multiline,
  label,
  required,
  type,
  placeholder,
  fieldRef,
  onClick,
  disabled,
  meta: { touched, error, warning }
}) => {
  delete input.value;

  function handleDrop(e) {
    e.preventDefault();
    e.stopPropagation();

    //this.unhighlight(e);
    let dt = e.dataTransfer;
    let files = dt.files;

    console.log("files", files);
    //this.handleFiles(files);
  }

  function highlight(e) {
    console.log("highlight");
    e.preventDefault();
    e.stopPropagation();
    //set highlight true
    //this.setState({ isHighlighted: true });
  }

  function unhighlight(e) {
    e.preventDefault();
    e.stopPropagation();
    //set highlight false
    //this.setState({ isHighlighted: false });
  }

  return (
    <FormControl component="fieldset" fullWidth={true}>
      <TextField
        label={required ? label + " *" : label}
        type={"file"}
        error={touched && (error && error.length > 0 ? true : false)}
        helperText={
          touched &&
          ((error && error.length > 0 ? error : null) ||
            (warning && warning.length > 0 ? warning : null))
        }
        InputLabelProps={{ shrink: true }}
        disabled={disabled}
        {...input}
      />

      <div
        className="dragndrop padded-zone"
        onDrageEnter={highlight}
        onDragOver={highlight}
        onDragLeave={unhighlight}
        onDrop={handleDrop}
        //ref={this.state.dropArea}
      >
        <div className="drop-area">xx</div>
      </div>
    </FormControl>
  );
};

export default renderDragDrop;

标签: javascriptreactjs

解决方案


您导入useState挂钩,并像这样使用它:


import React, { useState } from "react";

…
const renderDragDrop = ({…}) => {
  const [test, setTest] = useState('FOO') // 'FOO' is the optional default value;


  console.log(test) // 'FOO'
  setTest('BAR');
  console.log(test) // BAR
…


推荐阅读