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 />)} />
답변
Yuki가 이미 언급했듯이 onChange기능을 올바르게 사용했는지 확인하십시오 . 두 개의 매개 변수를받습니다. 설명서에 따르면 :
서명 :
function(event: object, value: any) => void.
event: 콜백의 이벤트 소스
value: null (자동 완성 구성 요소 내의 값 / 값).
예를 들면 다음과 같습니다.
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 },
];
답변
onChange올바르게 사용 했습니까?
onChange 서명 :function(event: object, value: any) => void
답변
D
입력 필드의 드롭 다운에서 선택한 항목을 표시하는 데 문제가있는 사람
해결 방법을 찾았습니다. 기본적으로 와 , 매끈한 머티리얼 UI 모두에 inputValueat 을 바인딩해야합니다 .onChageAutocompleteTextField
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 />
)}
/>
답변
<Autocomplete
disableClearable='true'
disableOpenOnFocus="true"
options={top100Films}
getOptionLabel={option => option.title}
onChange={this.onTagsChange}
renderInput={params => (
<TextField
{...params}
variant="standard"
label="Favorites"
margin="normal"
fullWidth
/>
)}
/>
위의 코드를 사용하면 선택한 옵션을 표시하는 자동 완성 상자를 여전히 얻을 수 없습니다. 아이디어가 있습니까?
답변
백엔드에서 태그를 얻으려면 모든 입력 변경에 대해 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 핸들러가 있습니다.
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:
}
};
답변
