programing

재료 UI에서 자동 완성 구성요소에 대한 변경 처리

i4 2023. 2. 20. 23:57
반응형

재료 UI에서 자동 완성 구성요소에 대한 변경 처리

사용하고 싶다Autocomplete컴포넌트를 지정합니다.태그를 가져와 나중에 데이터베이스에 저장할 수 있도록 상태에 저장하려고 합니다.나는 반응으로 수업 대신 함수를 사용하고 있다.제가 해봤는데onChange하지만 아무 결과도 얻지 못했습니다.

<div style={{ width: 500 }}>
  <Autocomplete
    multiple
    options={autoComplete}
    filterSelectedOptions
    getOptionLabel={(option) => option.tags}
    renderInput={(params) => (
      <TextField
        className={classes.input}
        {...params}
        variant="outlined"
        placeholder="Favorites"
        margin="normal"
        fullWidth
      />
    )}
  />
</div>;

유키 씨가 이미 언급했듯이onChange올바르게 기능합니다.2개의 파라미터를 수신합니다.설명서에 따르면:

서명:function(event: object, value: any) => void.

event: 콜백 이벤트소스

value: null(Autocomplete 컴포넌트 내의 값/값).

다음은 예를 제시하겠습니다.

import React from 'react';
import Chip from '@material-ui/core/Chip';
import Autocomplete from '@material-ui/lab/Autocomplete';
import TextField from '@material-ui/core/TextField';

export default class Tags extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tags: []
    };
    this.onTagsChange = this.onTagsChange.bind(this);
  }

  onTagsChange = (event, values) => {
    this.setState({
      tags: values
    }, () => {
      // This will output an array of objects
      // given by Autocompelte options property.
      console.log(this.state.tags);
    });
  }

  render() {
    return (
      <div style={{ width: 500 }}>
        <Autocomplete
          multiple
          options={top100Films}
          getOptionLabel={option => option.title}
          defaultValue={[top100Films[13]]}
          onChange={this.onTagsChange}
          renderInput={params => (
            <TextField
              {...params}
              variant="standard"
              label="Multiple values"
              placeholder="Favorites"
              margin="normal"
              fullWidth
            />
          )}
        />
      </div>
    );
  }
}

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 },
  { title: '12 Angry Men', year: 1957 },
  { title: "Schindler's List", year: 1993 },
  { title: 'Pulp Fiction', year: 1994 },
  { title: 'The Lord of the Rings: The Return of the King', year: 2003 },
  { title: 'The Good, the Bad and the Ugly', year: 1966 },
  { title: 'Fight Club', year: 1999 },
  { title: 'The Lord of the Rings: The Fellowship of the Ring', year: 2001 },
  { title: 'Star Wars: Episode V - The Empire Strikes Back', year: 1980 },
  { title: 'Forrest Gump', year: 1994 },
  { title: 'Inception', year: 2010 },
];

백엔드에서 태그를 가져오려면 입력 변경 시마다 API를 눌러야 했습니다.

입력 변경 시마다 제안된 태그를 가져오려면 Material-ui onInputChange를 사용하십시오.

this.state = {
  // labels are temp, will change every time on auto complete
  labels: [],
  // these are the ones which will be send with content
  selectedTags: [],
}
}

//to get the value on every input change
onInputChange(event,value){
console.log(value)
//response from api
.then((res) => {
      this.setState({
        labels: res
      })
    })

}

//to select input tags
onSelectTag(e, value) {
this.setState({
  selectedTags: value
})
}


            <Autocomplete
            multiple
            options={top100Films}
            getOptionLabel={option => option.title}
            onChange={this.onSelectTag} // click on the show tags
            onInputChange={this.onInputChange} //** on every input change hitting my api**
            filterSelectedOptions
            renderInput={(params) => (
              <TextField
                {...params}
                variant="standard"
                label="Multiple values"
                placeholder="Favorites"
                margin="normal"
                fullWidth
              />

사용하신 것이 확실합니까?onChange맞습니까?

onChange 시그니처:function(event: object, value: any) => void

@Dworo

[입력(Input)]필드의 드롭다운에서 선택한 항목을 표시하는 데 문제가 있는 경우

회피책을 찾았습니다. 기본적으로는,inputValueonChage쌍방에게Autocomplete그리고.TextField.

const [input, setInput] = useState('');

<Autocomplete
  options={suggestions}
  getOptionLabel={(option) => option}
  inputValue={input}
  onChange={(e,v) => setInput(v)}
  style={{ width: 300 }}
  renderInput={(params) => (
    <TextField {...params} label="Combo box" onChange={({ target }) => setInput(target.value)} variant="outlined" fullWidth />
  )}
/>

자동 완성에서 옵션을 선택할 때 상태를 업데이트하려고 했습니다.모든 입력을 관리하는 글로벌 onChange 핸들러가 있었다.

         const {name, value } = event.target;
         setTukio({
          ...tukio,
          [name]: value,
        });

그러면 필드 이름을 기반으로 개체가 동적으로 업데이트됩니다.그러나 자동 완성에서는 이름이 공백으로 반환됩니다.그래서 핸들러를 바꿔서onChange로.onSelect그런 다음 변경을 처리하기 위한 별도의 함수를 만들거나 내 경우와 같이 이름이 전달되지 않았는지 확인하기 위해 if 문을 추가합니다.

// This one will set state for my onSelect handler of the autocomplete 
     if (!name) {
      setTukio({
        ...tukio,
        tags: value,
      });
     } else {
      setTukio({
        ...tukio,
        [name]: value,
      });
    }

위의 방법은 단일 자동 완성일 경우 작동합니다.여러 개의 u가 있는 경우 다음과 같은 커스텀 함수를 전달할 수 있습니다.

<Autocomplete
    options={tags}
    getOptionLabel={option => option.tagName}
    id="tags"
    name="tags"
    autoComplete
    includeInputInList
    onSelect={(event) => handleTag(event, 'tags')}
          renderInput={(params) => <TextField {...params} hint="koo, ndama nyonya" label="Tags" margin="normal" />}
        />

// The handler 
const handleTag = ({ target }, fieldName) => {
    const { value } = target;
    switch (fieldName) {
      case 'tags':
        console.log('Value ',  value)
        // Do your stuff here
        break;
      default:
    }
  };

이 방법은 효과가 있었습니다.

유형 객체 배열이 있습니다.

{
   id: someId,
   label: someLabel,
}

이 어레이를 "paramed"라고 부릅니다.formState 오브젝트를 다음과 같이 사용합니다.

   const [formState, setFormState] = useState({
      idPuntoVenta: '',
      nomPuntoVenta: '',
      selected: items[0],
    });

그리고 Autocomplete 컴포넌트를 다음과 같이 정의했습니다.

<Autocomplete
    disablePortal
    id="salesPoint"
    options={sortedSalesPoints}
    value={selected}
    onChange={(event, newValue) => {
        setFormState({
            ...formState,
            selected: newValue,
            idPuntoVenta: newValue?.id,
        });
    }}
    inputValue={nomPuntoVenta}
    onInputChange={(event, newInputValue) => {
        setFormState({
            ...formState,
            nomPuntoVenta: newInputValue,
        });
    }}
    renderInput={(params) => (
        <TextField
            {...params}
            className="form-control"
            size="small"
            label="Punto de venta"
            required
        />
    )}
/>;

여기서 중요한 것은(그리고 잠시 시간이 걸린 것은) 자동 완성 컴포넌트의 {value} 속성이 어레이 "items"에 저장된 것과 동일한 유형의 개체임을 이해하는 것입니다.

언급URL : https://stackoverflow.com/questions/58684579/handle-change-on-autocomplete-component-from-material-ui

반응형