#javascript #html #css #reactjs #antd
#javascript #HTML #css #reactjs #antd
Вопрос:
Я использую Antd Reactjs (форма antd, ввод и выбор опции) для динамической генерации группы одинаковых полей, нажав кнопку ( отправить).Это работает правильно, но я хочу сгенерировать больше полей в соответствии с опцией, выбрав из поля выбора в конкретной строке, не изменяя другие поля всех строк. Я прикрепил изображения, чтобы вы могли легко ответить на этот запрос. динамически генерировать поля с помощью кнопки отправки
при выборе опции в поле выбора затем вызывается добавление нового поля (имя размера)
это код поля, который генерируется с помощью кнопки отправки динамически
<Form.List name="variant_rate">
{(fields, { add, remove }) => {
return (
<div>
{fields.map((field, index) => (
<Space
key={field.key}
style={{ display: "flex", marginBottom: 8 }}
align="start"
>
<Form.Item
{...field}
name={[field.name, "send_to"]}
fieldKey={[field.fieldKey, "send_to"]}
rules={[
{
required: true,
message: "Select where to send yarn",
},
]}
>
<Select
onChange={sendToChnage}
onSelect={() => onSelect(index)}
placeholder="Send to"
Options={SendToOption}
/>
{/* <Select
placeholder="Catagory"
Options={["A Catagory", "B Catagory", "C Catagory"]}
/> */}
</Form.Item>
{flag ? (
<Form.Item
{...field}
name={[field.name, "sizer_id"]}
fieldKey={[field.fieldKey, "sizer_id"]}
rules={[
{
required: true,
message: "Please select Sizer Name",
},
]}
>
<Select
placeholder="Sizer name"
type="sizerList"
Options={sizerList ? sizerList : [<LazyLoad />]}
/>
</Form.Item>
) : null}
<Form.Item
{...field}
name={[field.name, "yarn_for"]}
fieldKey={[field.fieldKey, "yarn_for"]}
rules={[
{
required: true,
message: "Select for which yarn received",
},
]}
style={{ width: "100%" }}
>
{/* <Input
placeholder="Quanitity"
/> */}
<Select
placeholder="Yarn Recieved For"
Options={["warp", "weft"]}
/>
</Form.Item>
<Form.Item
{...field}
name={[field.name, "slip_no_fac"]}
fieldKey={[field.fieldKey, "slip_no_fac"]}
rules={[
{
required: true,
message: "Factory Slip No is Required",
},
]}
style={{ width: "100%" }}
>
<Input
placeholder="Factoy Slip No"
// prefix={<UserOutlined />}
/>
</Form.Item>
<Form.Item
{...field}
name={[field.name, "fac_bag"]}
fieldKey={[field.fieldKey, "fac_bag"]}
rules={[
{
required: true,
message: "Please Enter Bags Quantity!",
},
]}
style={{ width: "100%" }}
>
<StyledInputNumber placeholder="bags" />
</Form.Item>
<Form.Item
{...field}
name={[field.name, "fac_cons"]}
fieldKey={[field.fieldKey, "fac_cons"]}
rules={[
{
required: true,
message: "Please Enter Cons Quantity!",
},
]}
style={{ width: "100%" }}
>
<StyledInputNumber placeholder="Cons" />
</Form.Item>
{/* {fields.length > 1 ? ( */}
<MinusCircleOutlined
onClick={() => {
remove(field.name);
}}
/>
{/* ) : null} */}
</Space>
))}
<Form.Item>
<Button
width="187px"
margin="auto"
fontSize="16px"
weight="500"
height="auto"
bg="#ba3d79"
onClick={() => {
add();
// setVariant(true);
}}
>
<PlusOutlined /> Send To
</Button>
</Form.Item>
</div>
);
}}
</Form.List>
это обработчик onChange, который срабатывает при выборе параметра в поле выбора
const sendToChnage = (value, index) => {
console.log("value,index", value, index);
if (value === "sizer") setFlag(true);
else setFlag(false);
};
это состояние, которое я использовал для скрытия или отображения нового поля (имя параметра)
const [flag, setFlag] = React.useState(false);
Ответ №1:
Я столкнулся с той же проблемой при разработке проекта, я сделал это с помощью событий javascript вот моя работа, которая поможет вам
$(document).on("change", "select.last", function () {
$("tr.productRow").each(function () {
$(this).removeClass("last");
$(this).addClass("first");
});
$("select.product").each(function () {
$(this).removeClass("last");
$(this).addClass("first");
});
$("input.last").each(function () {
$(this).attr("required", "required");
$(this).removeClass("last");
$(this).removeAttr("readonly");
$(this).addClass("first");
$(this).val(1);
});
var selectedProduct = $(this).children("option:selected");
var selectedProductPrice = $(this).children("option:selected").attr("data-price");
var Quantity = $(this).parent("td").siblings("td").children("input.quantity").val();
$(this).parent("td").next("td").children("input.price").val(selectedProductPrice);
$(this)
.parent("td")
.siblings("td")
.children("input.totalPrice")
.val(selectedProductPrice * Quantity);
$("#t_body").append(
'<tr class="last productRow"> <td> <select name="products[]" class="form-control product last select2" data-live-search="true" id="products"> <option value="" disabled selected>Choose Product</option> @foreach ($products as $key => $product) <option value="{{$product->id}}" data-price="{{ $product->price }}">{{ $product->name }}</option> @endforeach </select> </td> <td class="tdprice"> <input type="number" class="form-control price" name="price[]" min="0" readonly > </td> <td class="tdquantity"> <input type="number" class="form-control quantity last" name="quantity[]" min="0" readonly> </td> <td class="tdtotalPrice"> <input type="number" class="form-control totalPrice" id="totalPrice" name="totalPrice[]" min="0" readonly > </td> </tr>'
);
$(".select2").select2();
});
Здесь я выбираю продукт для создания счета-фактуры для клиента и динамически включаю поля для выбора другого продукта.
Сначала, когда вы выбираете любой продукт, он заменяет значения в соответствии с ценой и количеством продукта, и вы можете изменять количество столько, сколько захотите, а в следующем, когда я выбираю второй продукт, будет выполняться тот же код, но он ничего не изменит в первом выбранном продукте
$(document.body).on("change", "select.first", function () {
$(this).parent("td").siblings("td").children("input.quantity").val(1);
var selectedProduct = $(this).children("option:selected");
var selectedProductPrice = $(this).children("option:selected").attr("data-price");
var Quantity = $(this).parent("td").siblings("td").children("input.quantity").val();
$(this).parent("td").next("td").children("input.price").val(selectedProductPrice);
$(this)
.parent("td")
.siblings("td")
.children("input.totalPrice")
.val(selectedProductPrice * Quantity);
});
И этот код будет использоваться, когда мы снова изменим первый выбранный продукт на любой другой продукт, когда мы изменим продукт, он заменит значения в соответствии со значениями продукта, но i не влияет ни на какой другой выбранный продукт, поскольку вы можете просмотреть код.