Javascript 材料UI中的“getOptionSelected”和“getOptionLabel”是什么,请举例说明?
我正在浏览Mui文档,在Javascript 材料UI中的“getOptionSelected”和“getOptionLabel”是什么,请举例说明?,javascript,reactjs,material-ui,Javascript,Reactjs,Material Ui,我正在浏览Mui文档,在Autocomplete组件部分,我得到了两个props,getOptionLabel和getOptionSelected,我得到了定义,但没有正确理解。因此,如果有人能以一种简单的方式给我一个正确的定义,那就太好了。例如,使用getOptionLabel在下拉列表中显示文本 示例:自动完成数组 const top100Films = [ { title: 'The Shawshank Redemption', year: 1994 }, { title: 'Th
Autocomplete
组件部分,我得到了两个props
,getOptionLabel
和getOptionSelected
,我得到了定义,但没有正确理解。因此,如果有人能以一种简单的方式给我一个正确的定义,那就太好了。例如,使用getOptionLabel
在下拉列表中显示文本
示例:自动完成数组
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 }
}
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionLabel={(option) => option.year.toString()} // in the dropdown the option text will be year,if we use like option.title then it will show the title of the movie in dropdown
......
getOptionLabel
正如Kalhan所说,getOptionLabel在下拉列表中设置字符串标签。例如:
const users = [
{ userName: 'bob', age: 20, message:[...] },
{ userName: 'jane', age: 43, message:[...] },
{ userName: 'joe', age: 88, message:[...] },
}
<Autocomplete
id="combo-box-demo"
options={users}
getOptionLabel={(user) => user.userName }
例如,通过使用getOptionSelected,当从下拉列表中选择元素时,我可以获得完整的用户对象(还可以避免诸如“提供给Autocomplete的值无效…”之类的警告)
const用户=[
{用户名:'bob',年龄:20岁,留言:[……]},
{用户名:'jane',年龄:43岁,留言:[……]},
{用户名:'joe',年龄:88岁,留言:[……]},
}
user.userName}
getOptionSelected={(选项,值)=>option.userName===value.userName}
onChange={(事件,newValue)=>{
这个.setValue(newValue);
}}
//更多代码
设置值=(新值)=>{
console.log(newValue);//{userName:'jane',年龄:43岁,消息:[……]}
}
但是选项也可以这样做?有什么区别吗?选项是填充下拉列表所需的列表,而getOptionLabel
是决定应该在上面的下拉选项中显示哪些文本的事情,例如:year将显示为选项的文本,如果我更改getOptionLabel={(选项)=>option.title}
然后它会在下拉列表中以选项文本的形式显示标题。您可以在这个相关的回答中找到一些信息:Jenna,您能告诉我如何使用动态创建的GetOptions Selected选项吗?
const users = [
{ userName: 'bob', age: 20, message:[...] },
{ userName: 'jane', age: 43, message:[...] },
{ userName: 'joe', age: 88, message:[...] },
}
<Autocomplete
id="combo-box-demo"
options={users}
getOptionLabel={(user) => user.userName }
function(option: T, value: T) => boolean
const users = [
{ userName: 'bob', age: 20, message:[...] },
{ userName: 'jane', age: 43, message:[...] },
{ userName: 'joe', age: 88, message:[...] },
}
<Autocomplete
id="combo-box-demo"
options={users}
getOptionLabel={(user) => user.userName }
getOptionSelected={(option, value) => option.userName === value.userName }
onChange={(event, newValue) => {
this.setValue(newValue);
}}
// more code
setValue = (newValue) => {
console.log(newValue); // { userName: 'jane', age: 43, message:[...] }
}