最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create a ref and manually trigger onclick on a textfield in React hooks - Stack Overflow

programmeradmin1浏览0评论

I need to trigger click on <TextField> of material-UI manually on certain event. In React I'd have been creating a ref and then triggered onClick on that ref. How do I achieve this in React Hooks?

P.S In case you're wondering, why I need to do this, this is why: Material UI - The textfield in the search bar doesn't get clicked when search icon is clicked

I need to trigger click on <TextField> of material-UI manually on certain event. In React I'd have been creating a ref and then triggered onClick on that ref. How do I achieve this in React Hooks?

P.S In case you're wondering, why I need to do this, this is why: Material UI - The textfield in the search bar doesn't get clicked when search icon is clicked

Share Improve this question asked Sep 25, 2020 at 18:24 ABGRABGR 5,2754 gold badges34 silver badges55 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

You cannot simply assign a ref prop to the TextField and call it a day like what the other answers have described. ref only works on DOM elements such as <input/>. In a custom ponent you would normally need to use Forwarded Refs.

However, in your case, since you are using MUI TextField, they already expose a prop that enables you to attach the ref to its internal input element. The prop is inputRef.

function App() {

  const txtField = React.useRef(null);
 
  return(
    <div>
      <Button 
        variant="contained"
        color="primary"
        onClick={() => {
          txtField.current.focus()
          // at this point if you need to trigger click then invoke .click() instead
        }}>
        focus on text field
      </Button>
      
      <br/>
      
      <TextField inputRef={txtField} />
    </div>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<body>
  <div id="root"></div>

  <script src="https://unpkg./react@16/umd/react.development.js"></script>
  <script src="https://unpkg./react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg./babel-standalone@6/babel.min.js"></script>
  <script src="https://unpkg./@material-ui/core@latest/umd/material-ui.development.js"></script>
  <script type="text/babel">
    const { TextField, Button } = MaterialUI;
  </script>
</body>

Use react hook named useRef then pass the ref created to ref attribute or innerRef attribute.

const ref=React.createRef();

//click
ref.current.onclick=

<TextField ref={ref}/>
发布评论

评论列表(0)

  1. 暂无评论