可聚焦输入

有人可以帮我完成 FocusableInput 组件,以便如果 shouldFocus 属性为真,输入元素会在第一次渲染时自动获得焦点。

该组件应该使用 React Hooks。

const FocusableInput = (props) => {
  // Write your code here
  return <input />;
};

document.body.innerHTML = "<div id='root' />";
ReactDOM.render(<FocusableInput shouldFocus={true} />, document.getElementById("root"));
setTimeout(() => console.log(document.getElementById("root").innerHTML));
stack overflow Focusable Input
原文答案
author avatar

接受的答案

我相信应该这样做,

const FocusableInput = (props) => {
  const {shouldFocus} = props;
  return <input autoFocus = {shouldFocus} />;
};

document.body.innerHTML = "<div id='root' />";
ReactDOM.render(<FocusableInput shouldFocus={true} />, document.getElementById("root"));
setTimeout(() => console.log(document.getElementById("root").innerHTML));

答案:

作者头像

我知道你想要这个 TestDome 的答案,你可以试试下面的代码:

const FocusableInput = (props) => {
const { shouldFocus } = props;
const emailInputRef = React.useRef(shouldFocus);

React.useEffect(() => {
emailInputRef.current.focus();
}, []);
return <input ref={emailInputRef}/>;
};

document.body.innerHTML = "<div id='root' />";
ReactDOM.render(<FocusableInput shouldFocus={true} />, 
document.getElementById("root"));
setTimeout(() => console.log(document.getElementById("root").innerHTML));
作者头像
// React is loaded and is available as React and ReactDOM
// imports should NOT be used
const FocusableInput = (props) => {
  // Write your code here
  const { shouldFocus } = props;
const emailInputRef = React.useRef(shouldFocus);

React.useEffect(() => {
   shouldFocus&&emailInputRef.current.focus();
}, []);
return <input ref={emailInputRef} />;

};

document.body.innerHTML = "<div id='root' />";
ReactDOM.render(<FocusableInput shouldFocus={true} />, document.getElementById("root"));
setTimeout(() => console.log(document.getElementById("root").innerHTML));
作者头像
const FocusableInput = (props) => {
  const { shouldFocus } = props;
  const [focus, setFocus] = React.useState(shouldFocus);

  React.useEffect(() => {
    setFocus(shouldFocus);
  }, []);
  return <input autoFocus={focus} />;
};

document.body.innerHTML = "<div id='root' />";
ReactDOM.render(
  <FocusableInput shouldFocus={true} />,
  document.getElementById("root")
);
作者头像
const FocusableInput = ({ shouldFocus }) => {
  const inputref = React.useRef();

  React.useEffect(() => {
    if (inputref && shouldFocus) {
      inputref.current.focus();
    }
  }, []);

  return <input ref={inputref} />;
};

document.body.innerHTML = "<div id='root' />";
ReactDOM.render(
  <FocusableInput shouldFocus={true} />,
  document.getElementById("root")
);
setTimeout(() => console.log(document.getElementById("root").innerHTML));
作者头像
// React is loaded and is available as React and ReactDOM
// imports should NOT be used
const FocusableInput = ({shouldFocus}) => {
const emailInputRef = React.useRef();

React.useEffect(() => {
  if(shouldFocus){
    emailInputRef.current.focus();
  }
}, []);
return <input ref={emailInputRef}/>;
};