如何更改彼此不相关的组件的输入文本颜色?

问题描述 投票:0回答:1

我的组件遇到了这个问题,问题是我现在使用 3 个主要组件,一个称为 Page.jsx,另一个称为 Pencil.jsx,另一个是 PencilCase.js。

这是我的 Page.jsx 组件

import {  useState } from "react"
import { toPng } from "html-to-image"
import download from "downloadjs"


const Page = () => {


   //localStorage use it with te xt
   const [inputText, setText] = useState(
      window.localStorage.getItem('inputText')
   )
   function setLocalStorage(value) {
      try {
         setText(value)
         window.localStorage.setItem("inputText", value)
         console.log(value)
      } catch (error) {
         console.log(error)
      }
   }

   //localStorage use it with title
   const [inputTitle, setTitle] = useState(
      window.localStorage.getItem('inputTitle')
   )
   function setTitleStorage(value) {
      try {
         setTitle(value)
         window.localStorage.setItem('inputTitle', value) //(key,var)
      } catch (error) {
         console.log(error)
      }
   }

    const pngDownload = document.querySelector('.MainPage');
    function btnDownload(){
      toPng(pngDownload)
      .then(dataPng =>{
         download(dataPng, 'NotePad.png')
      })
      .catch(error=>console.log(error))
    }

   return (
      <>
         <section className="MainPage">
            <main id="MainContent">
               <header id="HeaderPage">
                  <input
                     type="text"
                     id="inputTitle"
                     placeholder="Insert Title"
                     value={inputTitle}
                     onChange={e => setTitleStorage(e.target.value)}
                     style={{color: `${inputText}`}}
                  />
                  <h2 id="TextTitle">
                     {inputTitle}
                  </h2>
               </header>
               <section className="TextContainer">

                  <textarea

                     placeholder="Insert Text"
                     name="textarea"
                     id="InputText"
                     onChange={e => setLocalStorage(e.target.value)}
                     value={inputText}
                     style={{color: `${inputText}`}}
                     >
                  </textarea>
                  <p
                     className="ShowText">
                     {inputText}
                  </p>
               </section>
            </main>
            

         </section>
         <button
               id="btnDownload"
               onClick={btnDownload}
            >
               <picture id="PrintContainer">
               <img id="PrintIcon"
                src="print-solid.svg"
                alt="Print Icon" />
               </picture>
               Print
            </button>
      </>
   )
}
export default Page

我试图从 PencilCase.js 组件设置文本颜色。

这是我的 PencilCase 组件:


import { useState } from "react"
import Pencil from "./Pencil"
import colors from "../../common/colors.js"


const PencilCase = () => {
    const [expand, setExpand] = useState(false)
    const [selectedColor, setSelectedColor] = useState(null);
    /*
  Create useState to passing the color from pencil to pencilCase

*/
    const handleColorClick = (color) => {
        setSelectedColor(color);
        // Save the selected color in local storage
        localStorage.setItem("inputText", color);
        console.log(selectedColor)
    };


    function handleOpen() {
        setExpand(
            prevValue => !prevValue
        )
    }


    return (
        <article id="PencilCaseContainer">
            <section
                onClick={handleOpen}
                id="ShowColor"
            >
                <picture
                    id="PaletteContainer">
                    <figure
                        id="ColorPalleteBehind">
                    </figure>
                    {/* <figure id="ColorPallete">*/}
                    <img
                        id="PaletteIcon"
                        src="palette-solid.svg"
                        alt="Palette Icon" />
                    {/*</figure>*/}
                </picture>
            </section>
            {expand &&
                <section
                    id="PencilCase">
                    <Pencil
                        colors={colors.black}
                        onClick={() => handleColorClick(colors.black)}
                    />
                    <Pencil
                        colors={colors.green}
                        onClick={() => handleColorClick(colors.green)}
                    />
                    <Pencil
                        colors={colors.yellow}
                        onClick={() => handleColorClick(colors.yellow)}
                    />
                    <Pencil
                        colors={colors.blue}
                        onClick={() => handleColorClick(colors.blue)}
                    />
                    <Pencil
                        colors={colors.red}
                        onClick={() => handleColorClick(colors.red)}
                    />
                </section>}
        </article>
    )
}

export default PencilCase

如您所见,我一直在尝试将选定的颜色从 PencilCase 组件传递到 Page 组件,但问题是它们两者都不相关。

<Pencil />
<PencilCase />
的子组件,所以这就是为什么我可以设置 props,但使用 Page.jsx 我不能这样做,因为它们都不是子组件。

这是我的另一个组件,您可以在其中看到组件关系

import Page from "./Page"
import PencilCase from "./PencilCase"


const NotePad= ()=>{

    return(
        <>
          <main className="BodyPad">
            <Page />
            <PencilCase />
          </main>
        </>
    )
}

export default NotePad

请大家帮助我:c

我一直在尝试创建一个 onClick 函数,因此每当单击

<Pencil />
组件时,颜色都可以保存为 localStorage 颜色,我可以在
<Page />
组件中使用它来设置 textColor 但它不起作用,我有一直在阅读有关它的内容,我尝试使用上下文和提供程序来执行此操作,但它不起作用。

css reactjs react-hooks styled-components react-context
1个回答
0
投票

问题似乎是父级上的

inputText
状态不会重新渲染,因此它没有设置颜色,据我所知这是预期的行为。要使
input
颜色发生变化并将值设置为 localStorage,您可以执行以下两件事:

1。将状态提升到父级

const NotePad = () => {
  const [inputColor, setInputColor] = useState()

  return (
    <main>
      <Page inputColor={inputColor}/>
      <PencilCase onChangeInputColor={(color) => setInputColor(color)}/>
    </main>
  )
}

const Page = ({inputColor}) => {
  return (
    <input style={{color: `${inputColor}`}} />
  )
}

const PencilCase = ({onChangeInputColor}) => {
  return (
   <>
    <Pencil onClick={() => onChangeInputColor(colors.black)}
   <>
  )
}

2。使用上下文共享状态

import * as React from "react";

const InputColor = React.createContext<{
  inputColor: string | null;
  setInputColor: (color: string | null) => void;
}>({} as any);

const useInputColor = () => React.useContext(InputColor);

const ColorProvider = ({ children }: { children: React.ReactNode }) => {
  const [inputColor, setInputColor] = React.useState<string | null>(null);

  return (
    <InputColor.Provider value={{ inputColor, setInputColor }}>
      {children}
    </InputColor.Provider>
  );
};

export const Context = () => {
  return (
    <ColorProvider>
      <div>
        <h3>Context</h3>
        <Page />
        <PencilCase />
      </div>
    </ColorProvider>
  );
};


const Page = () => {
  const { inputColor } = useInputColor();
  return (
    <div>
      <input
        defaultValue="Context"
        style={inputColor ? { color: inputColor } : {}}
      />
    </div>
  );
};

const PencilCase = () => {
  const { setInputColor } = useInputColor();
  return (
    <div style={{ display: "flex", gap: 10 }}>
      <Pencil bgColor="red" onClick={() => setInputColor("red")} />
      <Pencil bgColor="white" onClick={() => setInputColor("white")} />
      <Pencil bgColor="blue" onClick={() => setInputColor("blue")} />
    </div>
  );
};

这里是演示

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.