简体   繁体   English

React:将重点放在 componentDidMount 上,如何使用钩子来实现?

[英]React: set focus on componentDidMount, how to do it with hooks?

In React, with classes I can set the focus to an input when the component loads, something like this:在 React 中,我可以使用类在组件加载时将焦点设置为输入,如下所示:

class Foo extends React.Component {
    txt1 = null;

    componentDidMount() {
        this.txt1.focus();
    }

    render() {
        return (
            <input type="text"
                ref={e => this.txt1 = e}/>
        );
    }
}

I'm trying to rewrite this component using the new hooks proposal .我正在尝试使用新的hooks 提案重写此组件。

I suppose I should use useEffect instead of componentDidMount , but how can I rewrite the focus logic?我想我应该使用useEffect而不是componentDidMount ,但是如何重写焦点逻辑?

You can use the useRef hook to create a ref, and then focus it in a useEffect hook with an empty array as second argument to make sure it is only run after the initial render. 您可以使用useRef钩子创建一个ref,然后将它集中在一个useEffect钩子中,并将一个空数组作为第二个参数,以确保它只在初始渲染后运行。

 const { useRef, useEffect } = React; function Foo() { const txt1 = useRef(null); useEffect(() => { txt1.current.focus(); }, []); return <input type="text" ref={txt1} />; } ReactDOM.render(<Foo />, document.getElementById("root")); 
 <script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.production.min.js"></script> <div id="root"></div> 

According to official docs: https://reactjs.org/docs/hooks-reference.html#useref you can use useRef .根据官方文档: https : useRef你可以使用useRef

useRef returns a mutable ref object whose .current property is initialized to the passed argument ( initialValue ). useRef返回一个可变的 ref 对象,其.current属性被初始化为传递的参数( initialValue )。 The returned object will persist for the full lifetime of the component.返回的对象将在组件的整个生命周期内持续存在。

A common use case is to access a child imperatively:一个常见的用例是命令式访问孩子:

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

Essentially, useRef is like a “box” that can hold a mutable value in its .current property.本质上, useRef就像一个“盒子”,可以在其.current属性中保存可变值。

You might be familiar with refs primarily as a way to access the DOM.您可能熟悉 refs 主要是作为访问 DOM 的一种方式。 If you pass a ref object to React with <div ref={myRef} /> , React will set its .current property to the corresponding DOM node whenever that node changes.如果您使用<div ref={myRef} />将 ref 对象传递给 React,则每当该节点发生更改时,React 都会将其.current属性设置为相应的 DOM 节点。

However, useRef() is useful for more than the ref attribute.但是, useRef()不仅对ref属性有用。 It's handy for keeping any mutable value around similar to how you'd use instance fields in classes.保持任何可变值类似于在类中使用实例字段的方式,这很方便。

This works because useRef() creates a plain JavaScript object.这是有效的,因为useRef()创建了一个普通的 JavaScript 对象。 The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render. useRef()和自己创建一个{current: ...}对象之间的唯一区别是 useRef 将在每次渲染时为您提供相同的 ref 对象。

Keep in mind that useRef doesn't notify you when its content changes.请记住, useRef 不会在其内容更改时通知您。 Mutating the .current property doesn't cause a re-render.改变.current属性不会导致重新渲染。 If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.如果您想在 React 将 ref 附加或分离到 DOM 节点时运行一些代码,您可能需要改用回调 ref。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 useRef 和 react 钩子在 ReactJS 中设置对自定义输入的关注? - How to set focus on custom input in ReactJS using useRef and react hooks? React Hooks:在componentDidMount上调度一个动作 - React Hooks: Dispatch an action on componentDidMount 如何在React中使用钩子实现componentDidMount以使其符合EsLint规则“ react-hooks / exhaustive-deps”:“ warn”? - How to implement componentDidMount with hooks in React to be in line with the EsLint rule “react-hooks/exhaustive-deps”: “warn”? React 函数/Hooks 组件上的 componentDidMount 等价物? - componentDidMount equivalent on a React function/Hooks component? 如何测试在componentDidMount中设置异步调用以设置React Component的状态 - How to TEST async calls made in componentDidMount that set the state of React Component 如何在孩子的 componentDidMount 反应中从父级设置变量? - How to set variable from parent inside child's componentDidMount react? 如何从React中的另一个函数为componentDidMount设置值? - How can I set value to componentDidMount from another function in React? 如何使用链式承诺测试react componentDidMount中的异步提取? - How do I test async fetch in react componentDidMount with chained promises? 如何将componentDidMount()与react-redux connect()混合使用? - How do you mix componentDidMount() with react-redux connect()? 如何在 React Hooks 中设置嵌套对象 - how to set a nested object in React Hooks
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM