简体   繁体   中英

How to reference another element found in a component from another component?

I'am trying to access the button element within my Calculator component from my Customize component. I am trying to get ahold of the button element so I can create another function that allow for customization, just like the other functions in my Customize component. I want change the buttons color from my customize component with javascript but it don't seem to work. I'm assuming my cust. comp.don't have access.I can sure use some help figuring this out.

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Calculator from "./Calculator";
import Navbar from "./Navbar";
import Customize from "./Customize";


const App = () => {
  return (
    <Router>
    <Navbar />
        <Route
          exact
          path="/"
          render={() => (
              <Calculator />
          )}
        />
        <Route
          exact
          path="/Customize"
          render={() => (
              <Customize />
          )}
        />
    </Router>
  );
};

export default App;

import { create, all } from "mathjs";
import React, { useState } from "react";
import "../css/Calculator.css";

const Calculator = () => {
  const [state, setState] = useState("0");
  const [calculation, setCalculation] = useState("");
  const config = {};
  const math = create(all, config);

  const handleClick = (e) => {
    const value = e.target.textContent;

    if (
      value === "=" &&
      (state !== "+" ||
        state !== "-" ||
        state !== "*" ||
        state !== "/" ||
        state !== "=")
    ) {
      const decimalIdx = calculation.indexOf(".");
      const distanceFromLastNum = calculation.length - 1 - decimalIdx;
      const total = calculation + state;
      setCalculation((prev) =>
        distanceFromLastNum <= 4
          ? `${prev}${state}=${
              math.round(math.evaluate(prev + state) * 10000) / 10000
            }`
          : `${prev}${state}=${math.evaluate(prev + state)}`
      );
      setState((math.round(math.evaluate(total) * 10000) / 10000).toString());
    }
    if (
      calculation.includes("=") === true &&
      (value === "+" || value === "-" || value === "*" || value === "/")
    ) {
      setCalculation(state + value);
      setState(value);
    } else if (calculation.includes("=") === true) {
      setCalculation("");
      setState(prev => value === "±" ? prev : "");
    }
    if (
      value === "±" &&
      state !== "+" &&
      state !== "-" &&
      state !== "*" &&
      state !== "/"
    ) {
      setState((prev) => (prev[0] !== "-" ? `-${prev}` : prev.slice(1)));
    }
    if (state.includes(".") === false && value !== "±" && value !== "=") {
      setState((prev) => prev + value);
    } else if (value !== "." && value !== "±" && value !== "=") {
      setState((prev) => prev + value);
    }

    if (
      state === "0" &&
      value !== "+" &&
      value !== "-" &&
      value !== "*" &&
      value !== "/" &&
      value !== "="
    ) {
      setState((prev) =>
        value === "±" && prev === "0"
          ? `-${prev}`
          : value === "±" && prev === "-0"
          ? prev
          : value
      );
      setCalculation("");
    } else if (
      value === "+" ||
      value === "-" ||
      value === "/" ||
      value === "*"
    ) {
      const lastChar = calculation[calculation.length - 1];
      if (
        lastChar === "+" ||
        lastChar === "-" ||
        lastChar === "/" ||
        lastChar === "*" ||
        lastChar === undefined
      ) {
        if (
          state === "+" ||
          state === "-" ||
          state === "*" ||
          state === "/" ||
          state === "." ||
          state === "-." ||
          state === "±" ||
          state === "="
        ) {
          setState(value);
        } else {
          setCalculation((prev) => prev + state + value);
          setState(value);
        }
      } else {
        setState(value);
      }
    } else {
      if (
        state === "+" ||
        state === "-" ||
        state === "*" ||
        state === "/" ||
        state === "±"
      ) {
        setState(value);
      } else {
        if (
          value !== "0" ||
          value !== "+" ||
          value !== "-" ||
          value !== "*" ||
          value !== "/" ||
          value !== "="
        ) {
          if (value !== "=" && value !== "±" && value === ".") {
            setState((prev) => (value === "." ? prev : prev + value));
          }
        }
      }
    }
    if (value === "C") {
      setState("0");
      setCalculation("");
    }
  };
  return (
    <div className="calculator">
      <div id="display" style={{ fontSize: "16px", height: "3.5vh" }}>
        {calculation}
      </div>
      <div id="display">{state}</div>
      <div className="divider"></div>
      <div className="calculator-buttons">
        <button className="btn" id="clear" onClick={(e) => handleClick(e)}>
          C
        </button>
        <button className="btn" id="conversion" onClick={(e) => handleClick(e)}>
          ±
        </button>
        <button className="btn" id="divide" onClick={(e) => handleClick(e)}>
          /
        </button>
        <button className="btn" id="multiply" onClick={(e) => handleClick(e)}>
          *
        </button>
        <button className="btn" id="seven" onClick={(e) => handleClick(e)}>
          7
        </button>
        <button className="btn" id="eight" onClick={(e) => handleClick(e)}>
          8
        </button>
        <button className="btn" id="nine" onClick={(e) => handleClick(e)}>
          9
        </button>
        <button className="btn" id="substract" onClick={(e) => handleClick(e)}>
          -
        </button>
        <button className="btn" id="four" onClick={(e) => handleClick(e)}>
          4
        </button>
        <button className="btn" id="five" onClick={(e) => handleClick(e)}>
          5
        </button>
        <button className="btn" id="six" onClick={(e) => handleClick(e)}>
          6
        </button>
        <button className="btn" id="add" onClick={(e) => handleClick(e)}>
          +
        </button>
        <button className="btn" id="one" onClick={(e) => handleClick(e)}>
          1
        </button>
        <button className="btn" id="two" onClick={(e) => handleClick(e)}>
          2
        </button>
        <button className="btn" id="three" onClick={(e) => handleClick(e)}>
          3
        </button>
        <button className="btn" id="equal" onClick={(e) => handleClick(e)}>
          =
        </button>
        <button className="btn" id="zero" onClick={(e) => handleClick(e)}>
          0
        </button>
        <button className="btn" id="decimal" onClick={(e) => handleClick(e)}>
          .
        </button>
      </div>
    </div>
  );
};

export default Calculator;

import "../css/Customize.css";
const Customize = ({tester}) => {
  const setBackgroundColor = () => {
    const color = document.getElementById("background").value;
    document.body.style.backgroundColor = color;
  };
  const setNavbarColor = () => {
    const color = document.getElementById("navbar").value;
    document.getElementsByTagName("nav")[0].style.backgroundColor = color;
  }
  return (
    <div className="flexbox">
      <div className="customize">
        <h5 style={{ color: "white" }}>Background </h5>
        <input type="color" id="background" />
        <button className="btn" id="color-button" onClick={setBackgroundColor}>
          Color Change
        </button>
      </div>
      <div className="customize">
        <h5 style={{ color: "white" }}>Navigation </h5>
        <input type="color" id="navbar" />
        <button className="btn" id="color-button" onClick={setNavbarColor}>
          Color Change
        </button>
      </div>
    </div>
  );
};

export default Customize;

Your issue is that you want to pass state around and have it changed in different component. In React world, without any library, you will have to define the variables/functions at the topper level of your two components, ie

App.js <- define your variables + functions
  |__ Customize.js <- pass in the variables as props
  |__ Calculator.js <- pass in the variables + function as props

Then you can manipulate it at Customize.js and the whole app will respond to the state change.

Of course, this will become very hard to manage once your app grow in size, therefore we usually use a global state management library to help us do that, to include a few for your research, you may use Redux , or React Context .

Notes: try to avoid using native JS DOM element in React because the lifecycle/nature of React makes it hard to manage the DOM element, such as your function can be trigger before the actual DOM is even loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM