Taro: 同级元素获取Input问题

Created on 17 Oct 2018  ·  6Comments  ·  Source: NervJS/taro

需求

image
点击Click事件让Input输入框获取焦点

源码

myInput: {}
  componentDidMount() {}
  clickMe() {
    console.log('myInput', this.myInput)
  }
  addRef(node) {
    this.myInput = node
  }
  render() {
    return (
      <View className="alert-content">
        <Input ref={this.addRef} style={{ width: '200px', border: '1px solid red' }} value={this.state.myTxt} />
        <View onClick={this.clickMe.bind(this)}>Click</View>
      </View>
    )
  }

尝试解决

  • 想通过ref拿到Input实例,再调用focus方法,代码如上所示,但是拿到的不是Input实例,是App
    image

1018更新:

  • 小程序端可以通过state中focus来控制Input是否获取焦点;
  • H5端经瞎蒙,也能找到dom:
const input = this.refs.input
const dom = input.vnode.dom

但是拿到的是vdom,不能使用focus()方法,其他办法拿到真实的dom就解决了

问题

其实现在的问题就变成了,怎么通过Taro的Input实例,拿到对应的真实DOM?

All 6 comments

遇到同样的问题,H5端输入框想要自动获取到焦点,点击搜索后自动blur,但现在就是没法获取到dom

@sunhaikuo 你截图中通过 ref 拿到的就是小程序 Input 组件的实例 NodesRef 对象,NodesRef 对象只能获取一些简单的属性,不能设置 focus。

@sunhaikuo @gmaso 要设置 focus,H5 和小程序端都应通过控制 Input 组件的 focus 属性,而不是通过ref。因为 Input 是一个封装的 react component,而不是浏览器的 input,即使为其添加 ref,也只能拿到一个 react component,上面是没有暴露 focus 方法的。

@Chen-jj 通过修改state来设置Input的focus来控制是否获取焦点,经测试小程序没有问题,但是H5没有效果
代码如下:

  clickMe() {
    this.setState({ focus: true })
  }
  render() {
    return (
      <View className="alert-content" style={{ padding: '20px' }}>
        <Input type="text" placeholder="我是Input" focus={this.state.focus} />
        <Button onClick={this.clickMe.bind(this)}>click</Button>
      </View>
    )
  }

@sunhaikuo 是的,文档有标明 H5 不支持 focus。

@Chen-jj 那现在想实现相同的效果,H5有什么好的解决方案没?

focus 事件已加,等发布最新版升级即可

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zhuxianguo picture zhuxianguo  ·  3Comments

GreatAuk picture GreatAuk  ·  3Comments

LadyChatterleyLover picture LadyChatterleyLover  ·  3Comments

rainbowMorelhahahah picture rainbowMorelhahahah  ·  3Comments

liuchuzhang picture liuchuzhang  ·  3Comments