如何将自定义React TypeScript元素强制转换为HTMLElement?

时间:2018-05-15 21:30:41

标签: reactjs typescript

我有一系列自定义元素,我想为所有这些元素存储一个ref,以便我可以故意在其中调用focus()。是否可以将自定义React元素转换为允许focus()

的DOM元素

SampleFeed.tsx

class Feed extends React.Component<{ posts: Post[] },{}> {
    private postRefs: Map<number, Post> = new Map<number, Post>();

    render() {
      <div>
         {this.props.posts.map(
          ((post: Post), (index: number)) =>
           <Post
            ref={(element: Post) => this.postRefs.set(index, element)}
            post={post}
          />)
         }
      </div>
    }

    focusTargetElement() {
      // Does not compile, "Property focus does not exist on Post"
      this.postRefs.get(5).focus();
    }
}

1 个答案:

答案 0 :(得分:0)

您没有发布Post组件的源代码,因此我将使用示例子组件呈现输入

选项1:

将元素ref存储在子组件中,并创建从父组件

调用的public focus()方法
class Post extends React.PureComponent {

  private ref: HTMLInputElement

  public render() {
    return <input ref={(ref) => this.ref = ref}/>
  }

  public focus() {
    this.ref.focus()
  }

}

https://codesandbox.io/s/4w0qrmjk37

选项2:

将回调方法传递给子组件props

class Post extends React.PureComponent<{setRef: (ref: HTMLInputElement) => void}> {

  public render() {
    return <input ref={(ref) => this.props.setRef(ref)}/>
  }

}

并将元素引用保留在父

class Feed extends React.Component<{ posts: Post[] },{}> {
    private postRefs: Map<number, HTMLInputElement> = new Map<number, HTMLInputElement>();

    render() {
      <div>
         {this.props.posts.map(
          ((post: Post), (index: number)) =>
           <Post
            setRef={(element: HTMLInputElement) => this.postRefs.set(index, element)}
            post={post}
          />)
         }
      </div>
    }

    focusTargetElement() {
      // Does not compile, "Property focus does not exist on Post"
      this.postRefs.get(5).focus();
    }
}

沙箱:https://codesandbox.io/s/v3o954jvyl