【问题标题】:How to trigger onChange manually in dropdown when values are pre-populated on page load in React当在 React 中的页面加载时预先填充值时,如何在下拉列表中手动触发 onChange
【发布时间】:2021-10-06 20:41:16
【问题描述】:

在触发 onChange 函数的下拉列表中单击值时,React 表单可以正常工作。但是,我正在尝试在页面加载时预填充下拉值(通过建立下拉列表之间的依赖关系),这就是我遇到的问题,即如果未手动修改 onChange 函数没有选择值。

我尝试使用下面的代码 sn-p 手动调用它,但 onChange 没有被触发。

        var element = document.getElementById("non_prod_env_id_textbox");
        var event = new Event('change');
        element.dispatchEvent(event);

这是我的完整代码。

import "./App.css";
import image from "./image/description.png";
import { Container, Button, Form } from "react-bootstrap";
import React, { useState } from "react";

import Amplify from "aws-amplify";
import { API } from "aws-amplify";

import { withAuthenticator, SignIn, ConfirmSignIn, Greetings, VerifyContact } from 'aws-amplify-react';
import MyTheme from "./components/AmplifyTheme";

import awsExports from "./aws-exports";
Amplify.configure(awsExports);

async function addData() {  
  const data = {
    body: {
      account_id: formState.account_id,
      app_id: formState.app_id,
      customer_id: formState.customer_id,
      customer_name: formState.customer_name,
      non_prod_environment_name: formState.non_prod_environment_name,
      non_prod_env_id: formState.non_prod_env_id,
      project_key: formState.project_key,
      parent_ou_id: formState.parent_ou_id,
      working_directory: formState.working_directory,
      request_status: "Pending",
    },
  };

  console.log(data);
  const apiData = await API.post("onboardapi", "/items", data);
  console.log({ apiData });
  alert("Request Submitted");
}

const formState = {
  account_id: "",
  app_id: "",
  message: "",
  customer_id: "",
  customer_name: "",
  non_prod_environment_name: "",
  non_prod_env_id: "",
  project_key: "",
  parent_ou_id: "",
  working_directory: "",
  request_status: "",
};

function updateFormState(key, value) {  
  formState[key] = value;
  if(document.getElementById("non_prod_environment_name_dropdown").value==='Other')
    {
        document.getElementById("non_prod_environment_name_textbox").disabled=false;

    }

  else if (document.getElementById("non_prod_environment_name_dropdown").value === 'Development')
    {
        document.getElementById("non_prod_env_id_textbox").value ='dev'; 
        var element = document.getElementById("non_prod_env_id_textbox");
        var event = new Event('change');
        element.dispatchEvent(event);
    }
  else if (document.getElementById("non_prod_environment_name_dropdown").value === 'Production')
    {
        document.getElementById("non_prod_env_id_textbox").value ='prd'; 
    }
  else if (document.getElementById("non_prod_environment_name_dropdown").value === 'Test')
    {
        document.getElementById("non_prod_env_id_textbox").value ='uat'; 
    }    
  else{
        document.getElementById("non_prod_environment_name_textbox").disabled=true;
      }
  
}


function App() {
  const [working_directory] = useState();
  const [parent_ou_id] = useState();
  const [project_key] = useState();
  const [non_prod_env_id] = useState();
  const [non_prod_environment_name] = useState();

  return (
    <Container>
      <div className="Title">
        <div className="Title-Subtitle">
          {" "}
          <h1>Self Service Account Onboarding</h1>
        </div>
      </div>

      <div>
        <h3>Account Onboard Request Parameters</h3>
        <img src={image} alt="Image" />
      </div>
      <div>
        <h3>Account Onboard Request Form</h3>
        <br />
        <Form>
          <Form.Group>
            <Form.Label>account_id</Form.Label>
            <Form.Control
              placeholder="account_id"
              onChange={(e) => updateFormState("account_id", e.target.value)}
            />
          </Form.Group>
          <Form.Group>
            <Form.Label>app_id</Form.Label>
            <Form.Control
              placeholder="app_id"
              onChange={(e) => updateFormState("app_id", e.target.value)}
            />
          </Form.Group>
          <Form.Group>
            <Form.Label>customer_id</Form.Label>
            <Form.Control
              placeholder="customer_id"
              onChange={(e) => updateFormState("customer_id", e.target.value)}
            />
          </Form.Group>
          <Form.Group>
            <Form.Label>customer_name</Form.Label>
            <Form.Control
              placeholder="customer_name"
              onChange={(e) => updateFormState("customer_name", e.target.value)}
            />
          </Form.Group>
          <Form.Group>
            <Form.Label>non_prod_environment_name</Form.Label>
            <select
              className="custom-select"
              id="non_prod_environment_name_dropdown"
              value={non_prod_environment_name}
              onChange={(e) =>
                updateFormState("non_prod_environment_name", e.target.value)
              }
            >
              <option value="Production">Default(Production)</option>
              <option value="Production">Production</option>
              <option value="Development">Development</option>
              <option value="Test">Test</option>
              <option value="Other">Other / Enter manually</option>
            </select>
          </Form.Group>
          <Form.Group>
            <Form.Label>non_prod_environment_name</Form.Label>
            <Form.Control
              placeholder="non_prod_environment_name enter manually"
              id="non_prod_environment_name_textbox"
              disabled="disabled"
              onChange={(e) => updateFormState("non_prod_environment_name", e.target.value)}
            />
          </Form.Group>
          <Form.Group>
            <Form.Label>non_prod_env_id</Form.Label>
            <select
              className="custom-select"
              id="non_prod_env_id_textbox"
              value={non_prod_env_id}
              onChange={(e) =>
                updateFormState("non_prod_env_id", e.target.value)
              }
            >
              <option value="prd">Default(prd)</option>
              <option value="dev">dev</option>
              <option value="prd">prd</option>
              <option value="uat">uat</option>
            </select>
          </Form.Group>

           <Form.Group>
            <Form.Label>project_key</Form.Label>
            <select
              className="custom-select"
              value={project_key}
              onChange={(e) => updateFormState("project_key", e.target.value)}
            >
              <option value="CUS">Default(CUS)</option>
              <option value="CUS">CUS</option>
              <option value="LAB">LAB</option>
            </select>
          </Form.Group>

          <Form.Group>
            <Form.Label>parent_ou_id</Form.Label>
            <select
              className="custom-select"
              value={parent_ou_id}
              onChange={(e) => updateFormState("parent_ou_id", e.target.value)}
            >
              <option value="r-xx1">Default(r-xx1)</option>
              <option value="r-xx2">r-mvhx (Production Org)</option>
              <option value="r-xx3">r-wmno (Test Org)</option>
            </select>
          </Form.Group>

          <Form.Group>
            <Form.Label>working_directory</Form.Label>
            <select
              className="custom-select"
              value={working_directory}
              onChange={(e) =>
                updateFormState("working_directory", e.target.value)
              }
            >
              <option value='"uat"'>"uat"</option>
              <option value='"dev"'>"dev"</option>
              <option value='"prd"'>"prd"</option>
            </select>
          </Form.Group>

          <Button onClick={addData}>Submit Request</Button>
        </Form>
      </div>
    </Container>
  );
}

// export default App;

export default withAuthenticator(App, false, [  //Comment this when testing locally
  <Greetings />,
  <SignIn />,
  <ConfirmSignIn />,
  <VerifyContact />,
], null, MyTheme)

【问题讨论】:

    标签: javascript html jquery reactjs


    【解决方案1】:

    您可以在 useState 函数中设置默认值。 只需将值传递给它,如下所示

    const [non_prod_env_id] = useState(‘prd’);

    您不需要手动将事件传递给 DOM,React 会自动将数据填充到 DOM 元素中。 事实上,这就是使用像 React 这样的 UI 框架的全部要点。

    您似乎对 vanilla JS 非常了解,但有些人在使用 React 时有一个错误的开始。 我建议您再阅读一遍 React 入门教程,以重新了解该框架。这将为您节省大量时间。 祝你好运

    【讨论】:

      【解决方案2】:

      感谢@datlt - 但是我后来通过手动更新表单状态发现了这个问题并且它起作用了。

        else if (document.getElementById("non_prod_environment_name_dropdown").value === 'Development')
      {
          document.getElementById("non_prod_env_id_textbox").value ='dev'; 
          element = document.getElementById("non_prod_env_id_textbox");
          formState["non_prod_env_id"] = element.value;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-28
        • 1970-01-01
        • 2014-02-22
        • 2014-06-18
        • 2012-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多