javascript - 如何将父组件的输入集中到子组件上?

标签 javascript reactjs focus parent

我正在使用 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} 当前:空 “引用”

我的问题:

  • 为什么这个值为空?
  • 如何聚焦输入?

Codesandbox

最佳答案

根据您的沙箱,您可以使用外部类 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/

相关文章:

javascript - 如何使用 backbonejs 和 requirejs 动态加载 View 和模板

javascript - 在移动设备上使用 skrollr 时网站无法完全滚动

javascript - 将 git 存储库重新安装为 React 包

CSS General sibling 不适用于 :focus?

javascript - 返回未定义的异步函数

javascript - Enyo 集合合并策略

javascript - ReactJS中动态生成的输入文本字段值设置问题

javascript - 将 Redux 与 ant design 表单结合使用的最佳解决方案

wpf - 如果我将 TextBox 聚焦在 ListView 项目内,如何选择该项目?

c# - 如何在 C# 中设置/更改/删除按钮上的焦点样式?