next.js 如何用另一个函数更改属性值?

agyaoht7  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(78)

我有一个组件在我的NextJs应用程序,我想改变子 prop (在这里命名为type)的子组件时,<input>元素是null
但我做不到有人想帮我谢谢。

"use client";
import { Icon } from "@iconify/react";
import "./_input-fragment.scss";

const InputFragment = (props) => {
  let variable;

  const checkVal = (value) => { // Everythink OK in this here.
    if (!value) {
      setData("error");
    }
  };

  const setData = (val) => {
    return (variable = val);
  };

  const Icn = (props) => {
    alert(props.type);
    if (props.type == "error") {
      return (
        <Icon
          icon="ph:seal-warning-fill"
          color="red"
        />
      );
    }
  };

  return (
    <>
      <div className="input-fragment">
        <label htmlFor={props.labelFor}>
          {props.labelName}
          <input
            id={props.labelFor}
            name={props.label}
            type={props.inputType}
            min={props.minLength}
            max={props.maxLength}
            defaultValue={"John Doe"}
            onBlur={() =>
              checkVal(document.getElementsByTagName("input")[0].value) <!-- When `input` is changed return value of `<input>` element to `checkVal()` function. -->
            }
          />
        </label>
        <Icn type={variable} /> // Dynamic update doesn't work.
      </div>
      <p className="message"></p>
    </>
  );
};

export default InputFragment;

字符串

x8goxv8g

x8goxv8g1#

组件不会重新渲染。我认为你可以在这种情况下使用useState钩子。

"use client";
import { useState } from "react";
import { Icon } from "@iconify/react";
import "./_input-fragment.scss";

const InputFragment = (props) => {
  const [variable, setVariable] = useState("");

  const checkVal = (value) => { // Everythink OK in this here.
    setVariable(value ? "": "error");
  };

  const Icn = () => {
    alert(variable);
    if (variable === "error") {
      return (
        <Icon
          icon="ph:seal-warning-fill"
          color="red"
        />
      );
    }
  };

  return (
    <>
      <div className="input-fragment">
        <label htmlFor={props.labelFor}>
          {props.labelName}
          <input
            id={props.labelFor}
            name={props.label}
            type={props.inputType}
            min={props.minLength}
            max={props.maxLength}
            defaultValue={"John Doe"}
            onBlur={(e) =>
              checkVal(e.target.value)
            }
          />
        </label>
        <Icn /> // Dynamic update doesn't work.
      </div>
      <p className="message"></p>
    </>
  );
};

export default InputFragment;

字符串

相关问题