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

前端 未结 1 1355
谎友^
谎友^ 2020-12-04 02:34

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 even

相关标签:
1条回答
  • 2020-12-04 03:22

    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.

    0 讨论(0)
提交回复
热议问题