javascript - 选择组件渲染
问题描述
我在反应中制作了一个自定义选择组件,它看起来像这样:
import { useDispatch, useSelector } from "react-redux";
const Select = ({
id,
options,
dispatchKey,
selector,
disabledOption = false,
}) => {
const dispatch = useDispatch();
const formValue = useSelector((state) => state.form[selector]);
return (
<select
id={id}
required
onChange={(e) => dispatch({ type: dispatchKey, value: e.target.value })}
value={'IT'}
className="mt-1 block form-select w-full py-2 px-3 py-0 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:shadow-outline-blue focus:border-blue-300 transition duration-150 ease-in-out sm:text-sm sm:leading-5"
>
{disabledOption && (
<option value="" disabled>
{disabledOption}
</option>
)}
{options &&
options.map((o) => (
<option value={o.value} key={o.value}>
{o.text}
</option>
))}
</select>
);
};
export default Select;
我这样使用它:
const countries = [
{ value: "NL", text: "Nederland " },
{ value: "BE", text: "Belgie " },
{ value: "DE", text: "Duitsland " },
{ value: "IT", text: "Italië " },
];
<Select
id="country"
options={countries}
dispatchKey="SET_COUNTRY"
selector="country"
disabledOption="Kies een land"
/>
此下拉列表显示国家/地区。现在我已经硬编码了“IT”。但是,当加载组件时,当我在另一个字段中键入内容时,它会显示“NL”,它会突然显示“IT”。
我在做什么错,为什么“IT”没有立即显示?
解决方案
我想我可以解释你的Select
组件的初始加载行为。
当您disabledOption
作为道具传递时,默认值false
设置为"Kies een land"
现在。
因此,当执行以下命令时:-
{disabledOption && (
<option value="" disabled>
{disabledOption}
</option>
)}
disabledOption
不是空字符串是真实的并且不会短路。
所以渲染了以下元素。
<option value="" disabled>
{disabledOption}
</option>
因为它是disabled
,所以显示的第一个条目countries
是NL
。
推荐阅读
- discord - 我如何通过在 discord.py 的 on_message 中提及他的名字来向某人发送 DM 消息
- c# - 使用 Moq 模拟接口属性
- sql-server - WITH 子句导致的 Azure SQL Server 查询错误
- sql - MS Access - 如何使用 3 个变量进行排名
- css - 为自定义样式选择引导活动选项卡标题
- python - Python 假设变量是本地的
- scala - scala重载解析函数调用和隐式搜索的区别
- python - 是否有一种“pythonic”方式来调整函数的定义?
- php - PHP Elasticsearch 7.9.2 字符串索引超出范围:0
- django - UpdateView 从一开始就可以在没有对象的情况下工作吗?