reactjs 以编程方式设置material-ui自动完成TextField中的值

2fjabf4q  于 2022-12-12  发布在  React
关注(0)|答案(5)|浏览(210)

在我的React应用程序中,我有一个可以从下拉列表中取值的输入,为此我使用了material-ui自动完成和TextField组件。

**问题:**如何通过单击按钮而不从下拉列表中选择来以编程方式设置输入值?例如,我想从示例中设置“教父”,该值应该在输入中可见。

Codesandbox example here

import React from "react";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { TextField, Button } from "@material-ui/core";

export default function ComboBox() {
  const handleClick = () => {
    // set value in TextField from dropdown list
  };

  return (
    <React.Fragment>
      <Autocomplete
        options={top100Films}
        getOptionLabel={option => option.title}
        style={{ width: 300 }}
        renderInput={params => (
          <TextField
            {...params}
            label="Combo box"
            variant="outlined"
            fullWidth
          />
        )}
      />
      <Button onClick={handleClick}>Set value</Button>
    </React.Fragment>
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 },
  { title: "The Dark Knight", year: 2008 }
];
rwqw0loc

rwqw0loc1#

可以将所需值存储在state中并将其传递给自动完成组件。
导入使用状态

import React, { useState } from 'react';

使用useState

const [val,setVal]=useState({})

单击按钮时更改值

const handleClick = () => {
    setVal(top100Films[0]);//you pass any value from the array of top100Films
   // set value in TextField from dropdown list
 };

并将此值传递给呈现中组件

<Autocomplete
   value={val}
    options={top100Films}
    getOptionLabel={option => option.title}
    style={{ width: 300 }}
    renderInput={params => (
      <TextField
        {...params}
        label="Combo box"
        variant="outlined"
        fullWidth

      />
    )}
  />
watbbzwu

watbbzwu2#

如果要在输入中显示默认的选定值,还必须设置Autocompelete组件的inputValue属性和onInputChange事件
状态变化:

const [value, setValue] = useState("");
const [inputValue, setInputValue] = useState("");

手柄点击变化

const handleClick = () => {
   setValue(top100Films[0]);
   setInputValue(top100Films[0]);
};

自动完成中的更改

<Autocomplete
    {...custom}
    value={value}
    inputValue={inputValue}
    onChange={(event, newValue) => {
      setValue(newValue);
    }}
    onInputChange={(event, newInputValue) => {
      setInputValue(newInputValue);
    }}

    options={top100Films}
    getOptionLabel={option => option.title}
    renderInput={(params) => (
      <TextField
        {...input}
        {...params}
        variant="outlined"
      />
    )}
  />
vfh0ocws

vfh0ocws3#

没有人给出正确答案...

const options = [
  { label: "A", value: 1 },
  { label: "B", value: 2 },
  { label: "A", value: 3 },
];

function MyInput() {
  const [value, setValue] = useState(options[0].value);

  return (
    <Autocomplete
      value={options.find((option) => option.value === value)}
      onChange={(_, v) => setValue(v?.value)}
      options={options}
      getOptionLabel={(option) => option.label}
      renderInput={(params) => (
        <TextField {...params}/>
      )}
    />
  )
}
cyej8jka

cyej8jka4#

如果您在这里尝试测试从MUI的Autocomplete组件调用的更改处理程序:
在setupTests.js文件中

import '@testing-library/jest-dom/extend-expect'

document.createRange = () => ({
  setStart: () => {},
  setEnd: () => {},
  commonAncestorContainer: {
    nodeName: 'BODY',
    ownerDocument: document
  }
})

在测试文件中:

import { render, fireEvent } from '@testing-library/react'

...

const { getByRole } = render(<MyComponentWithAutocomplete />)

const autocomplete = getByRole('textbox')

// click into the component
autocomplete.focus()

// type "a"
fireEvent.change(document.activeElement, { target: { value: 'a' } })

// arrow down to first option
fireEvent.keyDown(document.activeElement, { key: 'ArrowDown' })

// select element
fireEvent.keyDown(document.activeElement, { key: 'Enter' })

expect(autocomplete.value).toEqual('Arkansas')
expect(someChangeHandler).toHaveBeenCalledTimes(1)

有关更多示例,请查看tests in the library

fcipmucu

fcipmucu5#

如果下拉菜单中没有该选项,则会添加新选项

import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete, { createFilterOptions } from '@mui/material/Autocomplete';

const filter = createFilterOptions();

export default function FreeSoloCreateOption() {
  const [value, setValue] = React.useState(null);

  return (
    <Autocomplete
      value={value}
      onChange={(event, newValue) => {
        if (typeof newValue === 'string') {
          
          setValue({
            title: newValue,
          });
        } else if (newValue && newValue.inputValue) {
          // Create a new value from the user input
          top100Films.push({title: newValue.inputValue})
          setValue({
            title: newValue.inputValue,
          });
        } else {
          setValue(newValue);
        
        }
       
        
      
      }}
      filterOptions={(options, params) => {
        const filtered = filter(options, params);

        const { inputValue } = params;
        // Suggest the creation of a new value
        const isExisting = options.some((option) => inputValue === option.title);
        if (inputValue !== '' && !isExisting) {
          filtered.push({
            inputValue,
            title: `Add "${inputValue}"`,
          });
        }

        return filtered;
      }}
      selectOnFocus
      clearOnBlur
      handleHomeEndKeys
      id="free-solo-with-text-demo"
      options={top100Films}
      getOptionLabel={(option) => {
        // Value selected with enter, right from the input
        if (typeof option === 'string') {
          return option;
        }
        // Add "xxx" option created dynamically
        if (option.inputValue) {
          return option.inputValue;
        }
        // Regular option
        return option.title;
      }}
      renderOption={(props, option) => <li {...props}>{option.title}</li>}
      sx={{ width: 300 }}
      freeSolo
      renderInput={(params) => (
        <TextField {...params} label="Free solo with text demo" />
      )}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994 },
  { title: 'The Godfather', year: 1972 },
  { title: 'The Godfather: Part II', year: 1974 }
 
];

相关问题