gpt4 book ai didi

javascript - Material UI react 自动完成设置不同的标签和不同的值

转载 作者:行者123 更新时间:2023-12-02 20:53:29 25 4
gpt4 key购买 nike

我们可以在https://material-ui.com/components/autocomplete/处看到这个例子。

我想设置不同的选项标签和值。

就像这里使用的示例

    const defaultProps = {
options: top5Films,
getOptionLabel: (option) => option.title,
};

<Autocomplete
{...defaultProps}
id="auto-complete"
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
autoComplete
includeInputInList
renderInput={(params) => <TextField {...params} label="clearOnEscape" margin="normal"/>}
/>
const top5Films= [
{ 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 }
]

但是我有这样的数据:

const top5Films= [
{ id: 1, title: 'The Shawshank Redemption', year: 1994 },
{ id: 2, title: 'The Godfather', year: 1972 },
{ id: 3, title: 'The Godfather: Part II', year: 1974 },
{ id: 4, title: 'The Dark Knight', year: 2008 },
{ id: 5, title: '12 Angry Men', year: 1957 }
]

我想将 id 设置为值并将标题显示为标签。

最佳答案

看起来该对象已分配给该值。

因此将 id 设置为值会导致选项崩溃。

我通过以下方式使用对象的 id 进行进一步操作。

/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function Playground() {
const [value, setValue] = React.useState(null);
const [id, setId] = React.useState(null);
const [title, setTitle] = React.useState(null);

return (
<div>
<div>{`value: ${value}`}</div>
<div>{`id: ${id}`}</div>
<div>{`title: ${title}`}</div>

<br />
<div style={{ width: 300 }}>
<Autocomplete
options={top5Films}
getOptionLabel={option => option.title}
id="movies"
value={value}
onChange={(event, newValue) => {
console.log(newValue);
if (newValue) {
setValue(newValue);
setId(newValue.id);
setTitle(newValue.title);
}
}}
renderInput={params => (
<TextField {...params} label="Movies" margin="normal" />
)}
/>
</div>
</div>
);
}

// Top 5 films as rated by IMDb users. http://www.imdb.com/chart/top
const top5Films = [
{ id: 1, title: "The Shawshank Redemption", year: 1994 },
{ id: 2, title: "The Godfather", year: 1972 },
{ id: 3, title: "The Godfather: Part II", year: 1974 },
{ id: 4, title: "The Dark Knight", year: 2008 },
{ id: 5, title: "12 Angry Men", year: 1957 }
];

这目前有效,但始终欢迎最好的答案。

关于javascript - Material UI react 自动完成设置不同的标签和不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61545840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com