react-hook-form结合react-places-autocomplete部署后输入失效求助
react-places-autocomplete 与 react-hook-form、MUI TextField 配合生产构建后输入失效问题
我在项目中使用react-places-autocomplete库,搭配react-hook-form和MUI的TextField组件实现地址输入功能,遇到了以下问题:
- 实现逻辑:将TextField嵌套在PlacesAutocomplete组件内,通过react-hook-form的
register函数注册表单字段,在PlacesAutocomplete的onChange事件中调用setValue更新表单值 - 本地开发环境(运行
react-scripts start)一切正常:输入内容能同步更新TextField,调用getValue('address')能返回正确的{ address: 输入值 } - 生产构建环境(执行
npm install && yarn install && yarn build后部署)完全失效:TextField无法输入任何内容,getValue('address')始终返回{ address: '' }
LocationSearchInput组件代码
<PlacesAutocomplete value={address} onChange={handleChangeAddress} onSelect={handleSelect} > {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => ( <div> <CustomTextField {...register('address', { value: defaultAddress || '', })} {...getInputProps({ label: ( <FormattedMessage id="required" defaultMessage="{text}*" values={{ text: ( <FormattedMessage id="enter_address" defaultMessage="Enter address" /> ), }} /> ), fullWidth: true, className: 'location-search-input', error, helperText, })} /> <div className="autocomplete-dropdown-container">...</div> </div> )} </PlacesAutocomplete>
handleChangeAddress函数代码
const handleChangeAddress = async (addr) => { setValue('address', addr, { shouldTouch: true }) await trigger('address') if (!addr) { setValue('city', '', { shouldTouch: true }) await trigger('city') } }
内容的提问来源于stack exchange,提问作者Artem Karimov
相关产品推荐
相关产品推荐

