[英]How to change a value from parent component in a child component with useState React hook
So I am fetching random colors via fetch_API every time I click the button "Get Color"
, the colors get added into an array and are listed with the.map function where also every div containing the hex value of the color is colored in that color and the button itself is also colored in the latest color.因此,每次单击"Get Color"
按钮时,我都会通过 fetch_API 随机获取 colors,将 colors 添加到数组中并与 .map function 一起列出,其中每个包含颜色的十六进制值的 div 也以该颜色着色按钮本身也涂上了最新的颜色。 That works all fine.一切正常。 What I wanted to add was an input field where I manually enter a hex and if the hex exists it gets added to the array and if not it just displays an error.我想添加的是一个输入字段,我在其中手动输入一个十六进制,如果十六进制存在,它就会被添加到数组中,如果不存在,它只会显示错误。 Here is the code of the parent component (I also added drag and drop functionality to the array)这是父组件的代码(我还为数组添加了拖放功能)
![How it looks][1] ![看起来如何][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;
Now the component Form.js works in a way that has an useEffect
where it checks if the user pressed enter and if he did it calls the function addColor()
which should take the value of the input field with the useRef hook and check if it is a valid hex and if it is it should add it into the array of colors, but for some reason, I am getting an error saying "TypeError: Cannot read properties of undefined (reading 'map')"
whenever I type anything into the input field, but if it is empty it displays the alert and no error is shown.现在,组件 Form.js 以一种具有useEffect
的方式工作,它检查用户是否按下了回车键,如果他按下了,它会调用 function addColor()
,它应该使用 useRef 钩子获取输入字段的值并检查它是否是一个有效的十六进制,如果是,它应该将它添加到"TypeError: Cannot read properties of undefined (reading 'map')"
的数组中,但出于某种原因,每当我在输入字段,但如果它是空的,它会显示警报并且不会显示错误。 The code of the Form js component: 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;
What am I doing wrong here?我在这里做错了什么? I know I am missing the setColors()
in some way but how?我知道我在某种程度上错过了setColors()
但如何呢?
Does switching:是否切换:
<Form setColors={() => setColors()} />
to:到:
<Form setColors={setColors} />
Fix your issue?解决你的问题? You don't need to create an anonymous function here.您无需在此处创建匿名 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.