简体   繁体   English

如何从另一个组件引用在组件中找到的另一个元素?

[英]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.我想使用 javascript 从我的自定义组件更改按钮颜色,但它似乎不起作用。 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在 React 世界中,没有任何库,您必须在两个组件的顶层定义变量/函数,即

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.然后你可以在Customize.js操作它,整个应用程序将响应状态变化。

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 .当然,一旦您的应用程序变大,这将变得非常难以管理,因此我们通常使用全局状态管理库来帮助我们做到这一点,为了您的研究包括一些,您可以使用ReduxReact 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.注意:尽量避免在 React 中使用原生 JS DOM 元素,因为 React 的生命周期/性质使得管理 DOM 元素变得困难,例如您的函数甚至可以在实际 DOM 加载之前触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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