我正在使用 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>
)
);
在父级中,我使用 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>
);
}
我从控制台得到的是这样的:
对象 {当前:null}
当前:空
“引用”
我的问题:
- 为什么这个值为空?
- 如何聚焦输入?
最佳答案
根据您的沙箱,您可以使用外部类 Component 中的 ref
而不是 this.ref
。只需将其更改为
<Input
ref={ref}
/>
进入此
<Input
ref={this.ref}
/>
并且在onClick
函数中像这样
onClick = () => {
this.setState({ showOther: true });
console.log(this.ref, "ref");
this.ref.current.focus(); // change it
};
这是工作codesandbox ,享受吧!
关于javascript - 如何将父组件的输入集中到子组件上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671193/