标签 ""->/ “日志”->/logs "exec"->/exec 我想确保以名称等于“”和标签“/”的值开始主题,这是第一个,是我从数据库中-6ren">
gpt4 book ai didi

javascript - React js Material ui初始值等于 ""

转载 作者:行者123 更新时间:2023-12-04 10:25:21 24 4
gpt4 key购买 nike

我有一个带有主题的选择字段,主题例如如下:

  • 名称 -> 标签


  • ""->/
  • “日志”->/logs
  • "exec"->/exec

  • 我想确保以名称等于“”和标签“/”的值开始主题,这是第一个,是我从数据库中获取的值,因此我无法进行更改.

    你能帮我吗?

    链接: codesandbox

    代码:
    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>
    );
    }

    最佳答案

    您需要添加两个内容才能正常工作:

  • 您需要设置 Select prop displayEmptytrue以便它将空字符串值视为它仍应尝试显示的内容,而不是将其视为未选择任何内容。
  • 您需要设置 InputLabel prop shrinktrue ,这样即使当前值为 TextField是空字符串,它仍会将标签向上移动,而不是将其显示在“/”选项的顶部。

  • 以下是基于您的沙箱的工作示例:
    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>
    );
    }

    Edit Select with empty value as an option

    关于javascript - React js Material ui初始值等于 "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60652517/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com