How can I create a clickable first option in Material UI Labs Autocomplete

空扰寡人 提交于 2020-01-21 18:52:29

问题


Below you can find an example from the MUI docs on Autocomplete where I've passed a link to google, prior to the options list. However, I can't click that option, the event target is just the MuiAutocomplete, rather than the <a> I'm passing.

import React from "react";
import TextField from "@material-ui/core/TextField";
import Paper from "@material-ui/core/Paper";

import Autocomplete from "@material-ui/lab/Autocomplete";

const Link = ({ children }) => (
  <Paper>
    <a href="https://www.google.com/" rel="nofollow" target="_blank">
      Go to Google
    </a>
    {children}
  </Paper>
);

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" fullWidth />
      )}
      PaperComponent={Link}
    />
  );
}

https://codesandbox.io/s/material-demo-egi6p

Interestingly, passing open to the autocomplete

    <Autocomplete
      open // add this prop
      id="combo-box-demo"
      options={top100Films}

allows this to work as expected.

Currently, I'm using a onMouseDown to make this work but feel this is possibly a bad solution.


回答1:


You can fix this by adding:

      onMouseDown={event => {
        event.preventDefault();
      }}

to your link so that your Link component looks like:

const Link = ({ children, ...other }) => (
  <Paper {...other}>
    <a
      onMouseDown={event => {
        event.preventDefault();
      }}
      href="https://www.google.com/"
      rel="nofollow"
      target="_blank"
    >
      Go to Google
    </a>
    {children}
  </Paper>
);

A separate fix that I've included is passing through any additional props to the Paper component (via ...other). The Popper component passes props to the Paper component that control its positioning, so the positioning will be incorrect without this change.

The reason why event.preventDefault() is necessary, is because the focus is on the input prior to the click. One of the default effects of the mouse-down would be to change focus from the input to the link. The onBlur of the input would trigger a close of the listbox portion of the Autocomplete which means the link would no longer be present and it would not continue on to the onClick behavior of the link. Calling event.preventDefault() prevents the focus change from occurring.



来源:https://stackoverflow.com/questions/59291614/how-can-i-create-a-clickable-first-option-in-material-ui-labs-autocomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!