ReactJS-如何在ReactJS类组件中自动对具有可满足属性为true的元素自动对焦?

发布于 2025-01-26 08:21:52 字数 536 浏览 2 评论 0 原文

我在正在从事的项目中发现了这个P标签。这是我前端的输入字段。我并不是那么熟悉的p tag是一个输入字段,但是当我的组件加载时,我只是要在此p标签输入字段中自动将文本量放置,因此用户始终准备键入并知道在哪里输入。

      <div className="create-post">
        <p
          contentEditable={!this.props.isLoading}
          spellCheck="true"
          placeholder="Write a new post here"
          id="txtContent"
          onKeyUp={this.entSub}
          onDrop={this.dropDrag}
        ></p>
      </div>

我尝试仅将 autocous 作为p标签添加,但什么也没有发生。我想这仅在实际HTML输入字段中起作用。

I found this p tag in a project I'm working on. This serves as an input field in my front end. I'm not that familiar p tag's being an input field, but I'd just to have the textfocus automatically in this p tag input field when my components loads, so a user is always ready to type and knows where to type.

      <div className="create-post">
        <p
          contentEditable={!this.props.isLoading}
          spellCheck="true"
          placeholder="Write a new post here"
          id="txtContent"
          onKeyUp={this.entSub}
          onDrop={this.dropDrag}
        ></p>
      </div>

I tried just adding autoFocus as prop to the P tag, but nothing happens. I guess that works only in the real HTML input field.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

白色秋天 2025-02-02 08:21:52

您将需要使用 refs useref useref hook )&amp;然后只需 inputref.current.focus();

棘手的部分是如何将商人移至最后?

const textLength = inputRef.current.innerText.length;
const range = document.createRange();
const sel = window.getSelection();

range.setStart(inputRef.current.childNodes[0], textLength)
range.collapse(true)

sel.removeAllRanges()
sel.addRange(range)

完整代码

import React, { useRef, useEffect } from "react";
import "./styles.css";

export default function App() {
  const inputRef = useRef(null);
  useEffect(() => {
    inputRef.current.focus();
    // move caret to end
    const textLength = inputRef.current.innerText.length;
    const range = document.createRange();
    const sel = window.getSelection();

    range.setStart(inputRef.current.childNodes[0], textLength)
    range.collapse(true)
    
    sel.removeAllRanges()
    sel.addRange(range)

  }, [inputRef]);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div className="create-post">
        <p
          contentEditable
          spellCheck="true"
          placeholder="Write a new post here"
          id="txtContent"
          ref={inputRef}
        >
          Content Editable
        </p>
      </div>
    </div>
  );
}

完整的示例 on codesandbox

You will need to use refs (useRef hook) & then simply inputRef.current.focus();.

Tricky part is how to move the caret to the end?

const textLength = inputRef.current.innerText.length;
const range = document.createRange();
const sel = window.getSelection();

range.setStart(inputRef.current.childNodes[0], textLength)
range.collapse(true)

sel.removeAllRanges()
sel.addRange(range)

Full code

import React, { useRef, useEffect } from "react";
import "./styles.css";

export default function App() {
  const inputRef = useRef(null);
  useEffect(() => {
    inputRef.current.focus();
    // move caret to end
    const textLength = inputRef.current.innerText.length;
    const range = document.createRange();
    const sel = window.getSelection();

    range.setStart(inputRef.current.childNodes[0], textLength)
    range.collapse(true)
    
    sel.removeAllRanges()
    sel.addRange(range)

  }, [inputRef]);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div className="create-post">
        <p
          contentEditable
          spellCheck="true"
          placeholder="Write a new post here"
          id="txtContent"
          ref={inputRef}
        >
          Content Editable
        </p>
      </div>
    </div>
  );
}

Complete example on Codesandbox

幽蝶幻影 2025-02-02 08:21:52

请参阅评论以获取说明,请询问您是否有任何疑问。

另请注意,与 p 标签相比 span div 标签可能会有更多运气>。行为可能会因浏览器而异。

export class App extends React.Component {
  constructor(props) {
    super(props);
    this.editableRef = React.createRef(); // Create a ref
  }

  componentDidMount() {
    this.editableRef.current.focus(); // Runs only on mount to focus the element
  }

  render() {
    return (
      <div className="create-post">
        <p
          ref={this.editableRef} // Assign ref to your element
          contentEditable={!this.props.isLoading}
          spellCheck="true"
          placeholder="Write a new post here"
          id="txtContent"
          onKeyUp={this.entSub}
          onDrop={this.dropDrag}
        />
      </div>
    );
  }
}

See comments for explanation, and please ask if you have any questions.

Also note, you may have more luck with a span or div tag than a p tag when it comes to contentEditable. Behavior may vary across browsers.

export class App extends React.Component {
  constructor(props) {
    super(props);
    this.editableRef = React.createRef(); // Create a ref
  }

  componentDidMount() {
    this.editableRef.current.focus(); // Runs only on mount to focus the element
  }

  render() {
    return (
      <div className="create-post">
        <p
          ref={this.editableRef} // Assign ref to your element
          contentEditable={!this.props.isLoading}
          spellCheck="true"
          placeholder="Write a new post here"
          id="txtContent"
          onKeyUp={this.entSub}
          onDrop={this.dropDrag}
        />
      </div>
    );
  }
}

羁〃客ぐ 2025-02-02 08:21:52

要使元素焦点,您可以简单地使用HTML标签 Tabindex (在React, Tabindex 中):

  <div className="create-post">
  {/* Check out tabIndex below */}
    <p
      contentEditable={!this.props.isLoading}
      spellCheck="true"

      tabIndex={0}
      placeholder="Write a new post here"
      id="txtContent"
      onKeyUp={this.entSub}
      onDrop={this.dropDrag}
    ></p>
  </div>

Tabindex 接受整数值。值0意味着该元素在任何正值后都应集中。当负(确切值无关紧要)时,这意味着该元素无法通过顺序键盘达到。当阳性时,这意味着该元素应基于数字值定义的顺序(3在4之前焦点,依此类推)。

有关更多信息,您可以检查

To make an element focusable, you can simply use the html tag tabindex (in React, tabIndex):

  <div className="create-post">
  {/* Check out tabIndex below */}
    <p
      contentEditable={!this.props.isLoading}
      spellCheck="true"

      tabIndex={0}
      placeholder="Write a new post here"
      id="txtContent"
      onKeyUp={this.entSub}
      onDrop={this.dropDrag}
    ></p>
  </div>

tabindex accepts an integer value. The value 0 means that the element should be focusable after any positive values. When negative (the exact value doesn't matter), it means that the element is not reachable via sequential keyboard. When positive, it means that the element should be focusable based on an order defined by the value of the number (3 is focusable before 4, and so on and so forth.).

For more, you can check the official doc

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文