Estaba revisando la documentación de Mui, en la sección del componente Autocomplete obtuve dos props , getOptionLabel y getOptionSelected , de los cuales obtuve la definición pero no la entendí correctamente. Entonces, sería genial si alguien me puede dar la definición adecuada de una manera simple con un ejemplo.
getOptionLabel se usa para mostrar el texto en el menú desplegable
EX: matriz de autocompletar
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 ...... getOptionSelected esto se usa para determinar el valor seleccionado de una matriz dada
<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 darkergetOptionLabel Como dijo Kalhan, getOptionLabel establece la etiqueta de cadena en el menú desplegable.
Por ejemplo:
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 }Para aclarar, getOptionSelected se usa para determinar si el valor seleccionado (es decir, la cadena en el campo de texto de autocompletar cuando selecciona un elemento del menú desplegable) coincide con una opción (en este caso, el objeto de usuario) de la matriz de opciones.
De acuerdo con los documentos de Material-ui , getOptionSelected tiene la siguiente firma, donde la opción es la opción para probar y el valor es el valor para probar:
function(option: T, value: T) => booleanComo ejemplo, al usar getOptionSelected, puedo obtener el objeto de usuario completo cuando se selecciona un elemento del menú desplegable (también evita advertencias como "El valor proporcionado para Autocompletar no es válido...")
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:[...] } }