React input输入框defaultvalue/value值不生效,表单set默认值不生效

在React应用中,当设置表单初始值时,发现useState的defaultValue不起作用。正确的做法是利用form.setFieldsValue来设定表单输入框的默认值。在编辑状态下,通过条件判断来决定是否禁用输入框,并设置相应的默认值。
value={0}//value='0'不生效
  const [disableds, setDisableds] = useState(false) //编辑状态
   <Form.Item
                name="field1"
                label="ERP是否存在:"
                rules={[
                  {
                    required: true,
                    message: '请输入',}
                    ,
                ]}
              >
                <Radio.Group buttonStyle="solid">
                  <Radio value={'0'}></Radio>
                  <Radio value={'1'}></Radio>
            
                    
input输入框直接set默认值不生效
const [defaultValue, setdefaultValue] = useState('') //默认值
 useEffect(() => {
    if(!initialValue.id){
    setdefaultValue(10)
    }
       }, [visible])
//输入框数据
<Col span={12}>
              <Form.Item
                name="residualLimit"
                label="剩余额度"
                rules={[
                  {
                   required: true,
                    message: '请输入',
                  },
                ]}
              >
                <Input placeholder="请输入" defaultValue={defaultValue} allowClear disabled={!disableds} />
                   </Form.Item>
            </Col>}
此时set进去的默认值是不生效的,应该用以下方法进行赋予默认值
更改方法,直接使用 form.setFieldsValue对表单输入框进行赋值
  useEffect(() => {
    if(!initialValue.id){
      form.setFieldsValue({
        residualLimit:'0';
          setDisableds(true)
      })
    }else{
     setDisableds(true)
     }
       }, [visible])
       
    <Col span={12}>
              <Form.Item
                name="residualLimit"
                label="剩余额度"
                rules={[
                  {
                   required: true,
                    message: '请输入',
                  },
                ]}
              >
                <Input placeholder="请输入" defaultValue={residualLimit} allowClear disabled={!disableds} />
                   </Form.Item>
            </Col>}

import { Card, Typography, Table, Checkbox, Button, Form, Input } from 'antd' import React, { useState, useEffect } from 'react' const { Title } = Typography import { useQueryVehicleAlarmConfig, useSavingVehicleAlarm, } from '@/query/settings' export default function Index() { const { data, refetch } = useQueryVehicleAlarmConfig() const [editable, setEdit] = useState(false) // 控制是否可编辑 const [localData, setLocalData] = useState(null) // 用 state 保存可变数据 const [form] = Form.useForm() const [state, setState] = React.useState([]) const [ violationParkingCountThreshold, violationParkingCountTimeline, overSpeedCountThreshold, overSpeedCountTimeline, detainTimeThreshold, detainCountThreshold, occupationCountThreshold, alarmCountLevel_1, alarmCountLevel_2, alarmCountLevel_3, alarmCountThreshold_1, alarmCountThreshold_2, alarmCountThreshold_3, ] = state // 初始化 localData useEffect(() => { if (data?.rules.length) { const date = data?.rules.map(item => ({ id: item.id, name: item.name, })) console.log(date, 'data') setState(date) } if (data?.configs) { setLocalData(data.configs) } }, [data]) const handleCheckboxChange = (item, index) => e => { if (!localData) return const newData = [...localData] newData[index].sysVehicleAlarmSecurityList = newData[ index ].sysVehicleAlarmSecurityList.map(alarm => alarm.id === item.id ? { ...alarm, status: e.target.checked } : alarm ) setLocalData(newData) // 更新 state,触发重新渲染 } const columns = [ { title: '车辆等级', dataIndex: 'vehicleLevelName', key: 'vehicleLevelName', width: 120, align: 'center', }, { title: '告警类型', dataIndex: 'sysVehicleAlarmSecurityList', key: 'sysVehicleAlarmSecurityList', align: 'center', render: (list, record, index) => { return ( <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'center', }} > {list?.map(item => ( <div key={item.id}> <Checkbox checked={item.status} disabled={!editable} onChange={handleCheckboxChange(item, index)} > {item.name || '未知类型'} </Checkbox> </div> ))} </div> ) }, }, ] return ( <Card style={{ padding: '0 30px' }}> <Title level={4}>车辆等级告警</Title> <Table bordered columns={columns} dataSource={localData} rowKey="id" pagination={false} /> <Title level={4} style={{ marginTop: 30 }}> 黑名单规则 </Title> <Form form={form} layout="vertical" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} onFinish={() => {}} > <Form.Item label="" name="violationParkingMinutes" rules={[{ required: true, message: '请输入分钟数' }]} > <div style={{ display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap', }} > <span style={{ flexShrink: 0 }}>违停</span> <Input disabled={!editable} size="large" defaultValue={violationParkingCountTimeline?.name || ''} style={{ width: 100, textAlign: 'center' }} /> <span>分钟以内的所有违停只算1次</span> </div> </Form.Item> <Form.Item label="" name="overSpeedMinutes" rules={[{ required: true, message: '请输入分钟数' }]} > <div style={{ display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap', }} > <span style={{ flexShrink: 0 }}>超速</span> <Input disabled={!editable} defaultValue={overSpeedCountTimeline?.name || ''} size="large" style={{ width: 100, textAlign: 'center' }} /> <span>分钟以内的所有超速只算1次</span> </div> </Form.Item> <Form.Item label="" name="level1Count" rules={[{ required: true, message: '请输入次数' }]} > <div style={{ display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap', }} > <span style={{ flexShrink: 0 }}>黑名单Level-1</span> <span>每月违规【超速、违停、滞留】达到</span> <Input disabled={!editable} defaultValue={alarmCountThreshold_1?.name || ''} size="large" style={{ width: 100, textAlign: 'center' }} /> <span>次进入黑名单,限制入园</span> <Input disabled={!editable} defaultValue={alarmCountLevel_1?.name || ''} size="large" style={{ width: 100, textAlign: 'center' }} /> <span>天</span> </div> </Form.Item> <Form.Item label="" name="level2Count" rules={[{ required: true, message: '请输入次数' }]} > <div style={{ display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap', }} > <span style={{ flexShrink: 0 }}>黑名单Level-2</span> 每月违规【超速、违停、滞留】达到 <Input disabled={!editable} size="large" defaultValue={alarmCountThreshold_2?.name || ''} style={{ width: 100, textAlign: 'center' }} /> <span>次进入黑名单,限制入园</span> <Input disabled={!editable} defaultValue={alarmCountLevel_2?.name || ''} size="large" style={{ width: 100, textAlign: 'center' }} /> <span>天</span> </div> </Form.Item> <Form.Item label="" name="level3Count" rules={[{ required: true, message: '请输入次数' }]} > <div style={{ display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap', }} > <span style={{ flexShrink: 0 }}>黑名单Level-3</span> 每月违规【超速、违停、滞留】达到 <Input disabled={!editable} size="large" defaultValue={alarmCountThreshold_3?.name || ''} style={{ width: 100, textAlign: 'center' }} /> <span>次及以上进入黑名单,限制入园</span> <Input disabled={!editable} size="large" defaultValue={alarmCountLevel_3?.name || ''} style={{ width: 100, textAlign: 'center' }} /> <span>天</span> </div> </Form.Item> <div style={{ display: 'flex', justifyContent: 'center', }} > <Button type="primary" style={{ marginRight: 20, }} onClick={() => { setEdit(!editable) }} > 编辑 </Button> <Button type="primary" style={{ marginRight: 20, }} onClick={() => { // 保存逻辑 console.log('保存数据:', data) // 可以在这里调用保存接口 }} > 保存 </Button> <Button>取消</Button> </div> </Form> </Card> ) } 默认,同时还能正常修改
最新发布
08-01
<!-- <div class="row"> <div class="col-md-6"> <div class="mb-3"> <label for="start_time" class="form-label">开始时间</label> <input type="time" class="form-control" id="start_time" name="start_time" min="08:00" max="19:30" required> </div> </div> <div class="col-md-6"> <div class="mb-3"> <label for="end_time" class="form-label">结束时间</label> <input type="time" class="form-control" id="end_time" name="end_time" min="08:30" max="20:00" required> </div> </div> </div> --> 下面为新代码, 可以 通过 val 进行 给 end_time 、start_time 赋 <div class="row"> <div class="col-md-6"> <div class="mb-3"> <label for="start_time" class="form-label">开始时间</label> <div class="d-flex"> <select class="form-select me-2" id="start_hour" name="start_hour" required> {% for h in range(8, 21) %} <option value="{{ '%02d' % h }}">{{ '%02d' % h }}</option> {% endfor %} </select> <select class="form-select" id="start_minute" name="start_minute" required> <option value="00">00</option> <option value="30">30</option> </select> </div> </div> </div> <div class="col-md-6"> <div class="mb-3"> <label for="end_time" class="form-label">结束时间</label> <div class="d-flex"> <select class="form-select me-2" id="end_hour" name="end_hour" required> {% for h in range(8, 21) %} <option value="{{ '%02d' % h }}">{{ '%02d' % h }}</option> {% endfor %} </select> <select class="form-select" id="end_minute" name="end_minute" required> <option value="00">00</option> <option value="30">30</option> </select> </div> </div> </div> </div>
07-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值