自定义组件ref不支持字符串名称:Function components cannot have string refs in React

分类:Javascript| 发布:camnpr| 查看: | 发表时间:2024/1/26

 The error "Function components cannot have string refs" occurs when we use a string as a ref in a function component.

To solve the error use the useRef() hook to get a mutable ref object that you can use as a ref inside of the component.

 

function components cannot have string refs

import {useEffect, useRef} from 'react';

 

export default function App() {

  const refContainer = useRef(null);

 

  useEffect(() => {

    // 👇️ This is reference to input element

    console.log(refContainer.current);

 

    refContainer.current.focus();

  }, []);

 

  return (

    <div>

      <input type="text" id="message" ref={refContainer} />

    </div>

  );

}

 
import {useEffect, useRef} from 'react';
 
export default function App() {
  const refContainer = useRef(null);
 
  const refCounter = useRef(0);
 
  useEffect(() => {
    // 👇️ This is reference to input element
    console.log(refContainer.current);
    refContainer.current.focus();
 
    // 👇️ Incrementing ref value does not cause re-render
    refCounter.current += 1;
    console.log(refCounter.current);
  }, []);
 
 
  return (
    <div>
      <input type="text" id="message" ref={refContainer} />
    </div>
  );
}
 
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/javascript/2299.html