【发布时间】:2021-11-27 11:02:14
【问题描述】:
所以每次单击按钮"Get Color" 时,我都会通过 fetch_API 获取随机颜色,颜色会被添加到数组中并与 .map 函数一起列出,其中每个包含颜色十六进制值的 div 都会被着色该颜色和按钮本身也以最新颜色着色。这一切都很好。我想要添加的是一个输入字段,我在其中手动输入一个十六进制,如果十六进制存在,它将被添加到数组中,如果不存在,它只会显示一个错误。
这是父组件的代码(我还向数组添加了拖放功能)
![看起来如何][1]
import React, { useState } from "react";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import Form from "./Form";
var but = false;
const Colors = () => {
const [colors, setColors] = useState([]);
//fetch the color
const GetColors = async () => {
const response = await fetch("https://www.colr.org/json/color/random", {
cache: "reload",
});
const color = await response.json();
but = true;
//add into the array
if (color.new_color === null) {
alert("error");
return;
} else {
setColors([...colors, color.new_color]);
}
};
//Item reordering for drag and drop
function handleOnDragEnd(result) {
if (!result.destination) return;
const items = Array.from(colors);
const [reorderedItem] = items.splice(result.source.index, 1);
items.splice(result.destination.index, 0, reorderedItem);
setColors(items);
}
return (
<>
<h4>
<DragDropContext onDragEnd={handleOnDragEnd}>
<Droppable droppableId="colors">
{(provided) => (
<ul {...provided.droppableProps} ref={provided.innerRef}>
{colors.map((color, index) => {
return (
<Draggable
key={color}
draggableId={String(color)}
index={index}
>
{(provided) => (
<li
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
>
<div
className="item"
style={{ background: "#" + color }}
>
<h4>{color}</h4>
</div>
</li>
)}
</Draggable>
);
})}
{provided.placeholder}
</ul>
)}
</Droppable>
</DragDropContext>
</h4>
<button
type="button"
className="btn"
style={{
background: but ? "#" + colors[colors.length - 1] : "black",
}}
onClick={GetColors}
>
Get Color
</button>
<Form setColors={() => setColors()} />
</>
);
};
export default Colors;
现在组件 Form.js 以具有useEffect 的方式工作,它检查用户是否按下了回车,如果他按下了,它调用函数addColor(),该函数应该使用 useRef 获取输入字段的值挂钩并检查它是否是有效的十六进制,如果是,则应将其添加到颜色数组中,但由于某种原因,每当我在输入字段中输入任何内容时,我都会收到错误消息"TypeError: Cannot read properties of undefined (reading 'map')",但如果是清空它显示警报并且不显示错误。
Form js组件代码:
import React, { useEffect, useRef } from "react";
const Form = ({ setColors }) => {
const colorRef = useRef();
function addColor() {
var color = colorRef.current.value;
console.log(color);
if (color === "" || color === /^#[0-9A-F]{6}$/i.test("#AABBCC")) {
alert("This color does not exist! Type a color hex that exists.");
} else {
setColors((prevColors) => {
return [...prevColors, { color }];
});
}
colorRef.current.value = null;
}
useEffect(() => {
const listener = (event) => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
event.preventDefault();
addColor();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
return (
<>
<article>
<form className="form">
<div className="form-control">
<h4>
<label htmlFor="ColorHex">Enter hex:</label>
</h4>
<input ref={colorRef} type="text" id="hex" name="hex" />
</div>
</form>
</article>
</>
);
};
export default Form;
我在这里做错了什么?我知道我在某种程度上错过了setColors(),但是怎么办?
【问题讨论】:
标签: javascript reactjs