如何将注意力集中在来自父级的子组件上?

问题描述 投票:0回答:1

我正在使用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>
  )
);

在父母中我使用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"

我的问题:

  • 为什么这是空的?
  • 我如何关注输入?

Codesandbox

javascript reactjs focus parent
1个回答
2
投票

基于您的沙箱,您使用来自外部类组件的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,享受!

© www.soinside.com 2019 - 2024. All rights reserved.