【发布时间】:2019-04-14 01:10:27
【问题描述】:
我正在使用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>
);
}
我从控制台得到的是这样的:
Object {current: null}
current: null
"ref"
我的问题:
- 为什么这个为空?
- 如何集中输入?
【问题讨论】:
标签: javascript reactjs focus parent