javascript - 如何将默认值设置为来自前缀或输入字段的状态
问题描述
我在编辑表单中遇到问题,我必须在输入字段(前缀)上显示来自 api 的国家代码。显示后我需要获取该值并将其设置为状态。当 onchange 完成时,我从输入字段(前缀)中获取值,但我需要没有 onchange 的值。我的意思是下拉列表中的任何内容,我需要获取该值。我需要显示我使用表单提交的任何国家/地区代码。然后,如果用户需要更改国家代码,那么他将选择国家。根据国家选择,我需要显示国家代码并将其设置为状态。希望你能理解我的问题...
这是我的代码......
const [countryCode, setcountryCode] = useState([]) // I am setting Api data into this state
const [subscriber, setSubscriber] = useState({ // here I am getting data what ever I sent to backed...
countryCode: "",
)}
<Form.Control
className='add_option'
type='text'
name='CountryCode'
onChange={handleChange}
as="select" required >
{
countryCode.map((codes, idx) => (
<option
key={idx}
required
name='CountryCode'
className='add_opt'
value={codes.CountryCode}
defaultValue={codes.CountryCode}
>
{codes.countryCode1}
</option>
))
}
</Form.Control>
提前致谢.....
解决方案
您必须换一种方式思考:
不要“从输入字段中获取值”,而是使用 eg存储当前值useState
并设置值。Form.Control
value={ currentCountryCode }
请参阅:受控组件。
onChange
设置状态(例如setCurrentCountryCode()
),然后从Form.Control
状态中取回值。
然后,任何其他事件也可以设置状态(setCurrentCountryCode()
),任何其他功能都可以使用当前状态(currentCountryCode
)。
例如:
import React, { useEffect, useState } from 'react';
import Form from 'react-bootstrap/Form';
export const SelectValue = () => {
const [ currentCountryCode, setCurrentCountryCode ] = useState(''); // <-- store selected value in state
const [ countryCode, setcountryCode ] = useState([
{ countryCode: 'xx' },
{ countryCode: 'yy' },
{ countryCode: 'zz' },
]);
const handleChange = function( x ){
setCurrentCountryCode(x.target.value) // <-- set state by selected value
};
useEffect(()=>{
/*
fetchCurrentCountryCode().then((value)=>{ // <-- maybe fetch the current value, or something
setCurrentCountryCode( value ) // <-- set state by fetched value
})
*/
}, []);
useEffect(()=>{
console.log('currentCountryCode:', currentCountryCode); // <-- do what ever you want with most recent value
}, [ currentCountryCode ]);
return (<>
<Form.Control
type='text'
onChange={ handleChange }
as="select"
value={ currentCountryCode } // <-- set the value from state
>
{
countryCode.map((codes, idx) => (
<option
key={ idx }
value={ codes.countryCode }
>
{ codes.countryCode }
</option>
))
}
</Form.Control>
</>);
};
推荐阅读
- javascript - 如何将 DIV 连接到 JavaScript 更改
- android-espresso - 如何减慢 Espresso typeText() 的速度?
- css - 向 SVG 笔画动画添加箭头
- .net - SignalR 客户端未异步处理接收到的数据
- dynamic-programming - 硬币变化动态规划问题自上而下的记忆方法
- google-cloud-firestore - 当文档的日期/时间字段与当前时间匹配时,我们如何让 Firestore 触发事件?
- spring - 在 Docker 容器之间信任 HTTPS 证书
- javascript - JS:循环遍历字符串并将具有这些单词值的对象(一对一)添加到对象数组中
- python-3.x - 将 np.argsort() 的结果转换为元组
- r - 在 R 包中包含图像