KAL*_*ITA 15 javascript reactjs material-ui
我所经历的MUI文档,在Autocomplete组件部分我有两个props,getOptionLabel而getOptionSelected我得到了定义,但我没有正确理解它。因此,如果有人可以通过示例以简单的方式给我正确的定义,那就太好了
K.T*_*ess 21
getOptionLabel 用于在下拉列表中显示文本
EX:自动完成数组
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
......
Run Code Online (Sandbox Code Playgroud)
getOptionSelected 这用于确定给定数组的选定值
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionSelected={(option) => option.year === 1994}
....
//this will select all the option which has year as 1994 and make the background of that option darker
Run Code Online (Sandbox Code Playgroud)
Jen*_*nna 15
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 }
Run Code Online (Sandbox Code Playgroud)
澄清一下,getOptionSelected 用于确定所选值(即当您从下拉列表中选择项目时自动完成文本字段中的字符串)是否与选项数组中的选项(在本例中为用户对象)匹配。
根据Material-ui docs,getOptionSelected具有以下签名,其中 option 是要测试的选项, value 是要测试的值:
function(option: T, value: T) => boolean
Run Code Online (Sandbox Code Playgroud)
例如,通过使用 getOptionSelected,当从下拉列表中选择一个元素时,我可以获得完整的用户对象(也避免了诸如“提供给自动完成的值无效...”之类的警告)
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:[...] }
}
Run Code Online (Sandbox Code Playgroud)