React 如何制作一个具有固定值和动态值的输入字段

React how to make an input field with a fixed value combined with a dynamic value

关于我如何能像这个人在 React 中使用 Javascript 取得类似结果的任何解决方案?检查 link -> https://codepen.io/matheusls94/pen/WOdRPR

我有一个 inputfield/textfield(mui),当新用户想要注册一个新的 account/e-mail 地址时,它会向服务器发出 post 请求。我希望用户避免在输入字段中键入“@hotmail.com”,这应该是一个固定值,即 uneditable/unremovable。就像上面的 codepen link。

动态值示例 -> Testemail,固定值 -> @hotmail.com

  const [email, setEmail]=useState("");

 async function Register(e){
    let item = {email};
    e.preventDefault();
    setLoading(true);

    let result = await fetch("https://localhost:44334/api/Register",{
        method:"POST",
        headers:{
            "Accept": "text/plain",
            "Content-Type": "application/json-patch+json",
        },
        body:JSON.stringify(item),
    });
    result = await result.json();

return (
<>
 <Container className="mt-5">
            <Row>
                <Col lg={4} md={6} sm={12} className="text-center mt-5 p-3">
                    <img className="icon-img" src={loginIcon} alt="icon"/>
                    <Form onSubmit={Register}>
                        <Form.Group>
                            <Form.Label>E-Mail</Form.Label>
                            <input value={dynamicvalue+fixedvalue} type="text" required={true} onChange={(e) => setEmail(e.target.value)}  fullWidth />
                        </Form.Group>
</>
)

您可以将 "@hotmail.com" 附加到输入的 value 属性,并在更新状态时将其删除。检查输入值是否以 "@hotmail.com" 结尾,是否允许更新状态。

例子

function App() {
  const [email, setEmail] = React.useState("");

  const changeHandler = (e) => {
    const { value } = e.target;
    if (value.endsWith("@hotmail.com")) {
      const modValue = value.replace("@hotmail.com", "");
      setEmail(modValue);
    }
  };

  return (
    <div className="App">
      <input
        type="text"
        value={`${email}@hotmail.com`}
        onChange={changeHandler}
      />
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />

更新

How would I achieve this if the values in modValue was to include "@hotmail.com" ? instead of replacing it with an empty string? For some reason the input value "@hotmail.com" does not get included on the registered user, only the dynamic value.

正确。如果在别处使用,您需要将 "@hotmail.com" 追加回 email 值。

但你是对的,有一种方法可以初始化 email 状态 "@hotmail.com" 并执行相同的 .endsWith 测试和状态更新而无需字符串替换。

function App() {
  const [email, setEmail] = React.useState("@hotmail.com");

  const changeHandler = (e) => {
    const { value } = e.target;
    if (value.endsWith("@hotmail.com")) {
      setEmail(value);
    }
  };

  return (
    <div className="App">
      <input
        type="text"
        value={email}
        onChange={changeHandler}
      />
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />