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
};