繁体   English   中英

React js材质ui初始值等于“”

[英]React js material ui initial value equal to ""

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

  • 名称 -> 标签

  1. "" -> /
  2. “日志”-> /logs
  3. “执行”-> / exec

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

你能帮我吗?

链接:代码沙盒

代码:

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 道具displayEmpty设置为true以便它将空字符串值视为它仍应尝试显示的内容,而不是将其视为未选择任何内容。
  • 您需要将InputLabel 属性shrink设置为true ,这样即使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>
  );
}

以空值作为选项编辑选择

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM