【问题标题】:How to focus input on a child component from parent?如何将输入集中在父组件的子组件上?
【发布时间】: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"

我的问题:

  • 为什么这个为空?
  • 如何集中输入?

Codesandbox

【问题讨论】:

    标签: javascript reactjs focus parent


    【解决方案1】:

    根据您的沙盒,您使用外部类组件中的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,享受吧!

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 2021-09-20
      • 2019-11-29
      • 2022-11-23
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 2023-03-27
      • 2019-01-07
      相关资源
      最近更新 更多