Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将输入集中在父组件的子组件上?_Javascript_Reactjs_Focus_Parent - Fatal编程技术网

Javascript 如何将输入集中在父组件的子组件上?

Javascript 如何将输入集中在父组件的子组件上?,javascript,reactjs,focus,parent,Javascript,Reactjs,Focus,Parent,我使用React.forwardRef在我的子组件上设置ref,如下所示: const Input = React.forwardRef( ({ value, onChange, onKeyPress, placeholder, type, label, ref }) => ( <div style={{ display: "flex", flexDirection: "column" }}> <input ref={ref}

我使用
React.forwardRef
在我的子组件上设置
ref
,如下所示:

const Input = React.forwardRef(
  ({ value, onChange, onKeyPress, placeholder, type, label, ref }) => (
    <div style={{ display: "flex", flexDirection: "column" }}>
      <input
        ref={ref}
        style={{
          borderRadius: `${scale.s1}rem`,
          border: `1px solid ${color.lightGrey}`,
          padding: `${scale.s3}rem`,
          marginBottom: `${scale.s3}rem`
        }}
        value={value}
        onChange={onChange}
        onKeyPress={onKeyPress}
        placeholder={placeholder ? placeholder : "Type something..."}
        type={type ? type : "text"}
      />
    </div>
  )
);
我从控制台得到的是:

对象{current:null}
当前:空
“ref”

我的问题是:

  • 为什么这是空的
  • 如何集中输入

基于您的沙箱,您可以使用来自类外组件的
ref
,而不是
this.ref
。把它从

<Input
  ref={ref}
/>

这就是工作,享受吧

基于您的沙箱,您使用来自类外组件的
ref
,而不是
this.ref
。把它从

<Input
  ref={ref}
/>
这就是工作,享受吧

<Input
  ref={this.ref}
/>
 onClick = () => {
    this.setState({ showOther: true });
    console.log(this.ref, "ref");
    this.ref.current.focus(); // change it
  };