javascript - 在反应组件中设置状态而不是类
问题描述
我正在开发一个拖放组件 - 但我不确定您将如何在 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;
解决方案
您导入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
…
推荐阅读
- git - 带有邮箱补丁的 git-am 在包含求职信时失败
- android - Webview 键盘问题
- regex - 可变长度和频率的数字和字母的正则表达式解析
- python - 使用 django-filters 按嵌套外键字段过滤
- javascript - Material-UI Drawer 在平板电脑上的作用不同
- r - Position_dodge 与 preserve='single' 不对齐 geom_text
- abap - 在运行时更改 Dynpro 输出字段的可见长度?
- r - R 中面板数据的标准化 Beta
- react-native - 反应原生 chrome 调试器不显示 console.log 和默认日志
- opengl - 在计算着色器中将 int 正确转换为 uint