0
点赞
收藏
分享

微信扫一扫

React+Taro h5 解决ios机型input无法自动聚焦的问题

彪悍的鼹鼠 2022-03-12 阅读 67
1、原因
2、方案
3、需求
4、思路
(4.1)、步骤一
const SearchArea = (props) => {
    const {
        show = true,
        callback = () => {}
    } = props;

    const [curInputVal, setCurInputVal] = useState('');

    // 监听input值变化
    const handleInputValue = (val) => {
        setCurInputVal(val)
    }

    // 点击手机键盘搜索框触发的函数
    const handleFinishForm = () => {
        intoSearchResult()
    }

    // 跳往搜索结果
    const intoSearchResult = () => {
        if(!curInputVal.trim()) return;
        Taro.navigateTo({
            url: 'pages/searchResult/index' + `?searchVal=${curInputVal}`
        })
    }

    return (
        <View className='search-area' style={{display: show ? 'flex' : 'none'}}>
            <View className='header-center-search' onClick={() => { callback() }}>
                <Form action="." onFinish={handleFinishForm}> // 自动调起手机键盘,务必得有Form
                     <Input
                         type="search" 
                         value={curInputVal}
                         placeholder='请输入您想查找的商品' 
                         maxLength={100}
                         onChange={handleInputValue}
                     />
                 </Form>
            </View>
            <View 
                className='search-btn'
                onClick={() => {
                    intoSearchResult()
                }}
            >搜索</View>
        </View>
    )
}

export default SearchArea;
(4.2)、步骤二
constructor(props) {
    super(props)
    this.state = {
      headerInfo: {}
    }
}
componentDidMount() {
    eventBus.on('setHeaderSearchInfo', (res) => {
      this.setState({
        headerInfo: res
      });
    });
  }
render () {
    return (
      <Provider store={store}>
        <SearchArea {...this.state.headerInfo}></SearchArea>
        {this.props.children}
      </Provider>
    )
}
(4.3)、步骤三
// index 页面
useDidShow(() => {
    eventBus.emit('setHeaderSearchInfo', {
      show: true,
      isNoNeedVal: true,
      callback: () => {
        Taro.navigateTo({
          url: 'pages/search/index',
        })
      }
    });
})
5、温馨提示
componentDidMount() {
    eventBus.on('setHeaderSearchInfo', (res) => {
      let id = getCurrentInstance().router.path;
      let element = document.getElementById(id);
      if(element) {
        if(res.show) {
          element.style.paddingTop = Taro.pxTransform(100)
        } else {
          element.style.paddingTop = Taro.pxTransform(0)
        }
      }
      this.setState({
        headerInfo: res
      });
    });
 }
6、售后服务
举报

相关推荐

0 条评论