[英]React js material ui initial value equal to ""
I have a select field, with topics, the topics are for example the following:我有一个带有主题的选择字段,主题例如如下:
I would like to make sure to start the topic as a value with the name equal to "" and the label "/", that is the first one, are values that I take from the db so I can't make changes.我想确保以名称等于“”和标签“/”的值开始主题,这是第一个,是我从数据库中获取的值,因此我无法进行更改.
Can you help me out?你能帮我吗?
Link: codesandbox链接:代码沙盒
Code:代码:
import React from "react";
import "./styles.css";
import { TextField, MenuItem } from "@material-ui/core";
export default function App() {
const [state, setState] = React.useState({
pubtopic: "",
subscriptions: [
{
name: "",
label: "/"
},
{
name: "exec",
label: "/exec"
},
{
name: "log",
label: "/log"
}
]
});
const { pubtopic, subscriptions } = state;
const onChange = name => ({ target: { value } }) => {
setState(prev => ({
...prev,
[name]: value
}));
};
return (
<div className="App">
<TextField
id="pubtopic"
select
label="Topic"
placeholder="Topic"
variant="outlined"
value={pubtopic}
onChange={onChange("pubtopic")}
size="small"
fullWidth
>
{subscriptions.map((el, key) => (
<MenuItem key={key} value={el.name}>
{el.label}
</MenuItem>
))}
</TextField>
pubtopic: {pubtopic}
</div>
);
}
You need two additions for this to work decently:您需要添加两个内容才能正常工作:
displayEmpty
to true
so that it will treat an empty string value as something that it should still try to display instead of treating it as meaning that nothing is selected.displayEmpty
设置为true
以便它将空字符串值视为它仍应尝试显示的内容,而不是将其视为未选择任何内容。shrink
to true
, so that even when the current value of the TextField
is empty string it will still move the label up rather than presenting it over the top of the "/" option.shrink
设置为true
,这样即使TextField
的当前值为空字符串,它仍会将标签向上移动,而不是将其显示在“/”选项的顶部。 Below is a working example based on your sandbox:以下是基于您的沙箱的工作示例:
import React from "react";
import "./styles.css";
import { TextField, MenuItem } from "@material-ui/core";
export default function App() {
const [state, setState] = React.useState({
pubtopic: "",
subscriptions: [
{
name: "",
label: "/"
},
{
name: "exec",
label: "/exec"
},
{
name: "log",
label: "/log"
}
]
});
const { pubtopic, subscriptions } = state;
const onChange = name => ({ target: { value } }) => {
setState(prev => ({
...prev,
[name]: value
}));
};
return (
<div className="App">
<TextField
id="pubtopic"
select
label="Topic"
variant="outlined"
value={pubtopic}
onChange={onChange("pubtopic")}
size="small"
fullWidth
SelectProps={{ displayEmpty: true }}
InputLabelProps={{ shrink: true }}
>
{subscriptions.map((el, key) => (
<MenuItem key={key} value={el.name}>
{el.label}
</MenuItem>
))}
</TextField>
pubtopic: {pubtopic}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.