我正在使用 SolidJS 和 SUID(Solid Material UI)库。
我正在尝试使用与 SUID 文档中相同的示例。
https://suid.io/components/select
import { For, createResource, createSignal } from 'solid-js';
import { Select, MenuItem } from '@suid/material'; // or "solid-ui", based on the library's exports
function Post() {
const [postsResource, { mutate, refetch }] = createResource(async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
});
// State for the selected option
const [selectedOption, setSelectedOption] = createSignal('any');
return (
<div>
<h1>Posts</h1>
{postsResource.loading && <p>Loading...</p>}
{postsResource.error && <p>Error: {postsResource.error.message}</p>}
{
<>
<Select
// defaultValue={'any'}
// value={selectedOption()}
onChange={(e) => {
console.log('onChange', e.currentTarget);
setSelectedOption(e.currentTarget.value);
}}
>
<MenuItem value="any">Choose any...</MenuItem>
<MenuItem value="option1">option1</MenuItem>
<MenuItem value="option2">option2</MenuItem>
<For each={postsResource()}>
{(post) => <MenuItem value={post.id}>{post.title}</MenuItem>}
</For>
</Select>
</>
}
</div>
);
}
export default Post;
在这种情况下,具有
any
、option1
和 option2
(静态选项)等值的选项是可选的,但其他选项则不可以。
我为您提供了stackblitz游乐场供您进行实验。
我还应该提到,当我使用静态选项(下面的代码)时,选择效果很好。
const options = [
{id: 1, label: 'Option 1'},
{id: 2, label: 'Option 2'},
{id: 3, label: 'Option 3'},
];
但是当我使用动态选项(fetch、
createResource
、promise 等)时,就会出现问题。
主要存在以下问题:
onChange
处理程序总是收到相似的值MUI: A component is changing the uncontrolled value state of Select to be controlled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled Select element for the lifetime of the component.
The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.
我尝试:
defaultValue
设置为 Select
;defaultValue
来创建信号;tabIndex
,因为我注意到在For
中每个MenuItem
都有tabIndex=-1
我的期望是什么:
来自
createResource
的值将是 undefined
,直到请求解析为某个值。因此,组件 For
最初接收 undefined
。您应该相应地重组您的组件。最好使用带有resource.state值的Switch/Match来进行条件渲染。