[英]How to focus input on a child component from parent?
I'm using React.forwardRef
to set a ref
on my Child component, like so: 我正在使用
React.forwardRef
在我的Child组件上设置一个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>
)
);
In the parent I use const ref = React.createRef()
and then call it: 在父级中,我使用
const ref = React.createRef()
,然后调用它:
onClick = () => {
this.setState({ showOther: true });
console.log(this.ref, "ref");
this.ref.focus();
};
render() {
return (
<div className="App">
<button onClick={this.onClick}>Click me</button>
<Input
ref={ref}
value={this.state.value}
onChange={this.handleChange}
onKeyPress={this.handleKeyPress}
placeholder="Type something..."
/>
</div>
);
}
What I get from the console is this: 我从控制台得到的是:
Object {current: null} current: null "ref"
My questions: 我的问题:
Based on your sandbox, You use ref
from outside class Component instead this.ref
. 根据您的沙箱,使用外部类Component的
ref
代替this.ref
。 Just change it from 只需从
<Input
ref={ref}
/>
into this 进入这个
<Input
ref={this.ref}
/>
and inside onClick
function to be like this 和里面的
onClick
函数是这样的
onClick = () => {
this.setState({ showOther: true });
console.log(this.ref, "ref");
this.ref.current.focus(); // change it
};
this is the working codesandbox , enjoy! 这是工作代码框 ,请尽情享受!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.