在“日期”文本字段中自定义默认值反应材料

时间:2019-06-19 06:43:23

标签: reactjs material-ui react-material

我是Material UI的新手。因此,在这里我使用的是Textfield类型的Date。默认情况下,在文本字段中显示“ dd-mm-yyyy”。但是,我想默认显示一个字符串值,例如“添加DOB(MM / DD / YYYY)”。我尝试了一些方法,它不采用字符串值。请让我知道,我如何实现这一目标。

import React from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';


const App = () => (
  <div style={styles}>
    <TextField
                                id="date"
                                label="Add Date of Birth"
                                type="date"
                                name="DateOfBirth"
                                defaultValue="Add DOB"
                                className="form-field"
                                InputLabelProps={{
                                    shrink: true,
                               }}
                            />
  </div>
);

render(<App />, document.getElementById('root'));

1 个答案:

答案 0 :(得分:0)

我不确定您要问的默认值是什么。我在这里假设两件事:日期的默认值或日期附带的某种文本。

如果要为TextField设置默认值,则最好为具有value={stateValue}状态的组件设置值prop。如果要在日期旁边添加一些文本,可以在“材质”用户界面中尝试Input Adornments

代码示例:

import React from "react";
import InputAdornment from "@material-ui/core/InputAdornment";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const useStyles = makeStyles(theme => ({
  container: {
    display: "flex",
    flexDirection: "column",
    flexWrap: "wrap"
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200
  },
  adornment: {
    width: 110
  },
  dense: {
    marginTop: 19
  },
  menu: {
    width: 200
  }
}));

export default function TextFields() {
  const classes = useStyles();
  const [values, setValues] = React.useState({
    date: "1993-11-01"
  });

  const handleChange = name => event => {
    console.log(event.target.value);
    setValues({ ...values, [name]: event.target.value });
  };

  return (
    <form className={classes.container} noValidate autoComplete="off">
      <TextField
        id="date"
        label="Add Date of Birth"
        type="date"
        name="DateOfBirth"
        // defaultValue="Add DOB"
        InputProps={{
          startAdornment: (
            <InputAdornment className={classes.adornment} position="start">
              Add DOB
            </InputAdornment>
          )
        }}
        value={values.date}
        className={classes.textField}
        onChange={handleChange("date")}
        InputLabelProps={{
          shrink: true
        }}
      />

      <TextField
        id="standard-name"
        label="Date Text"
        className={classes.textField}
        value={values.date}
        onChange={handleChange("date")}
        margin="normal"
      />
    </form>
  );
}

演示代码和框TextField - date