React-动态表单字段,其中字段根据下拉菜单更改(使用挂钩)

时间:2019-12-30 16:46:20

标签: javascript reactjs

我有一种表单,希望根据从下拉列表中选择的类别来呈现不同的字段。例如,在下面的示例中,如果存在名为“电话”和“笔记本电脑”的类别,则如果选择了“笔记本电脑”,则表单将包括“网络”字段,如果选择了“笔记本电脑”,则表单将包括“处理器”字段(当前均显示)。这样做的最佳方法是什么?我认为我需要将选定的下拉选项存储在状态中并根据该字段呈现字段,但是我在如何完成它而不破坏我现有内容的情况下迷失了。

import React, { useState, useEffect } from "react";
import Layout from "../core/Layout";
import { isAuthenticated } from "../auth";
import { createProduct, getCategories } from './apiAdmin';

const AddProduct = () => {
  const [values, setValues] = useState({
    name: '', network: '',  processor: '', categories: [], category: '', loading: false, error: '', createdProduct: '', redirectToProfile: false, formData: ''
  });
  const { user, token } = isAuthenticated();
  const { name, network, processor, categories, category, loading, error, createdProduct, redirectToProfile, formData } = values;

  const init = () => {
    getCategories().then(data => {
      if (data.error) {
        setValues({ ...values, error: data.error });
      } 
      else {
        setValues({...values, categories: data, formData: new FormData() });
      }
    });
  };

  useEffect(() => {
    init();
  }, []);

  const handleChange = name => event => {
    const value = event.target.value;
    formData.set(name, value);
    setValues({ ...values, [name]: value });
  };

  const clickSubmit = (event) => {
    event.preventDefault();
    setValues({ ...values, error: '', loading: true });
    createProduct(user._id, token, formData)
      .then(data => {
        if (data.error) {
          setValues({ ...values, error: data.error });
        }
        else {
          setValues({ ...values, name: '', network: '', processor: '', loading: false, createdProduct: data.model });
        }
      });
  };

  const newPostForm = () => (
    <form className='mb-3' onSubmit={clickSubmit} >
      <div className='form-group'>
        <label className='text-muted'>Category</label>
        <select onChange={handleChange('category')} className='form-control'>
          <option>Select a Category</option>
          { categories && categories.map((c, i) => (<option key={i} value={c._id}>{c.name}</option>)) }
        </select> 
      </div>    
      <div className='form-group'>
        <label className='text-muted'>Name</label>
        <input 
          onChange={handleChange('name') } 
          type='text' 
          className='form-control' 
          value={name} 
        /> 
      </div>    

      // *****************************************************************************************
      // ************  THIS SHOULD BE RENDERED ONLY IF CATEGORY 'PHONES' IS SELECTED  ************
      // *****************************************************************************************

      <div className='form-group'>
        <label className='text-muted'>Network</label>
        <input 
          onChange={handleChange('network') } 
          type='text' 
          className='form-control' 
          value={network} 
        /> 
      </div>

      // *****************************************************************************************
      // ***********  THIS SHOULD BE RENDERED ONLY IF CATEGORY 'LAPTOPS' IS SELECTED  ************
      // *****************************************************************************************
      <div className='form-group'>
        <label className='text-muted'>Processor</label>
        <input 
          onChange={handleChange('processor') } 
          type='text' 
          className='form-control' 
          value={processor} 
        /> 
      </div>
      <button className='btn btn-outline-primary'>
        Submit
      </button>
    </form>
  );

  return (
    <Layout title='Add Product' description={`Welcome, ${user.name}.`} >
      <div className='row'>
        <div className='col-md-8 offset-md-2'>
          {newPostForm()}
        </div>
      </div>
    </Layout>
  )
}

export default AddProduct;

2 个答案:

答案 0 :(得分:1)

这应该对您有用:

{
  "command": "multiCommand.insertLineCommentEOL",
  "sequence": [
    "cursorLineEnd",
    {
      "command": "editor.action.insertSnippet",
      "args": {
        "snippet": "  $LINE_COMMENT $1"
      }
    }
  ]
}

答案 1 :(得分:1)

这将为您提供帮助。

  

formData.get("category") === "phones" ? <> PHONES DISPLAY DIV </> : formData.get("category") === "laptops" ? <> LAPTOPS DISPLAY DIV</> : null