react Input 的defaultValue不随着state变化

前端之家收集整理的这篇文章主要介绍了react Input 的defaultValue不随着state变化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

第一次遇到input的defaultValue不会变化,或者只记录前一次的数据,后面的数据不会及时更新,而value是不能改变input的值的

解决办法就是给父级的div或者form添加一个可变的key值

class TeacherInfoWidget extends React.Component{
  render(){
    const {onChange,teacherInfo,No,newKey}=this.props;
    const mobNum='mobNum';
    const startYear='startYear';
    const name='name';
    const gender='gender';
    // const connectinfo='connectinfo';
    const onInputChange = (field) => {
      return e => {
        const { currentTarget: { value } } = e;
        if (onChange) {
          onChange({field,value});
        }
      }
    }
    const onSelectChange = (field) => {
      return value => {
        if (onChange) {
          onChange({field,value});
        }
      }
    }
    return (
      <div className='teacherInfo-model' key={ No =='1' ? newKey :teacherInfo._id || No }>
        <div className='model-row'>
          <label htmlFor="">登录名</label>
          <Input placeholder="登录名" className='text-type' defaultValue={No == '1'? '' :teacherInfo.mobNum} onChange={onInputChange(mobNum)}/>
        </div>
        <div className='model-row'>
          <label htmlFor="">入职年份</label>
          <InputNumber min={1970} max={2100} defaultValue={No == '1'? '' : teacherInfo.startYear} onChange={onSelectChange(startYear)}/>
        </div>
        <br/>
        <div className='model-row'>
          <label htmlFor="">姓名</label>
          <Input placeholder="姓名" className='text-type' defaultValue={No == '1'? '' : teacherInfo.name} onChange={onInputChange(name)}/>
        </div>
        <div className='model-row'>
          <label htmlFor="">性别</label>
          <Select  style={{ width: 60 }} defaultValue={teacherInfo.gender== 'M' ? '男' : '女'} onChange={onSelectChange(gender)} >
            <Option key='1'value="M">男</Option>
            <Option key='2' value="F">女</Option>
          </Select>
        </div>
        <br/>
        {/*<div className='model-row'>*/}
          {/*<label htmlFor="">联系方式</label>*/}
          {/*<Input placeholder="联系方式" className='text-type' onChange={onInputChange(connectinfo)}/>*/}
        {/*</div>*/}
      </div>
    );
  }
}
原文链接:https://www.f2er.com/react/303051.html

猜你在找的React相关文章