Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 函数式组件里 Input 组件无法受控 #10509

Closed
TheKonka opened this issue Oct 27, 2021 · 2 comments
Closed

React 函数式组件里 Input 组件无法受控 #10509

TheKonka opened this issue Oct 27, 2021 · 2 comments
Labels
F-react Framework - React T-weapp Target - 编译到微信小程序 V-3 Version - 3.x

Comments

@TheKonka
Copy link
Member

相关平台

微信小程序

复现仓库

https://github.com/konka-king/test-input-component
小程序基础库: 2.20.1
使用框架: React

复现步骤

React函数式组件,在 Input 组件中输入值,代码里 通过 onInput 事件接收 处理并修改不合法的值,但是 实际上并没有修改成功;
使用class类编写时,相同处理代码,效果正常

期望结果

输入的不合法值被修改

实际结果

输入的不合法值没有被修改

环境信息

👽 Taro v3.3.11


  Taro CLI 3.3.11 environment info:
    System:
      OS: macOS 12.0.1
      Shell: 5.8 - /bin/zsh
    Binaries:
      Node: 14.16.1 - /usr/local/bin/node
      Yarn: 1.22.10 - /usr/local/bin/yarn
      npm: 7.20.0 - /usr/local/bin/npm
    npmPackages:
      @tarojs/components: 3.3.11 => 3.3.11 
      @tarojs/mini-runner: 3.3.11 => 3.3.11 
      @tarojs/react: 3.3.11 => 3.3.11 
      @tarojs/runtime: 3.3.11 => 3.3.11 
      @tarojs/taro: 3.3.11 => 3.3.11 
      @tarojs/webpack-runner: 3.3.11 => 3.3.11 
      babel-preset-taro: 3.3.11 => 3.3.11 
      eslint-config-taro: 3.3.11 => 3.3.11 
      react: ^17.0.0 => 17.0.2 

补充信息

函数式组件,通过正则 match 方法 处理 onInput 事件 e.detail.value,返回 RegExpMatchArray 类型的数组,若直接将返回的数组 setstate, 效果反而正常受控?!

@taro-bot2 taro-bot2 bot added F-react Framework - React T-weapp Target - 编译到微信小程序 V-3 Version - 3.x labels Oct 27, 2021
@TheKonka TheKonka changed the title Input 组件无法受控 React 函数式组件里 Input 组件无法受控 Oct 27, 2021
@GrapevineLin
Copy link

我猜是你没有在视图变化的时候及时更新状态,可以看看这个 #2642

@TheKonka
Copy link
Member Author

我猜是你没有在视图变化的时候及时更新状态,可以看看这个 #2642

感谢回复,可能就是setdata 相同的值,没有触发diff 原因

const handleAmountInput = (e: BaseEventOrig<InputProps.inputEventDetail>) => {
    const amount = e.detail.value.match(/^\d+(?:\.\d{0,2})?/);
    setPaymentAmount(e.detail.value);
    setTimeout(() => {
      setPaymentAmount(amount ? amount[0] : "");
    });
    // return amount ? amount[0] : "";
  };

参照 #2642 (comment) 这个例子 ,这样修改可以解决我的问题;

不过 后面 @Chen-jj 又说了 可以忽略上面的回答(#2642 (comment) ) 对应的文档在 http://taro-docs.jd.com/taro/docs/1.x/debug/#%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E8%A1%A8%E5%8D%95%E7%BB%84%E4%BB%B6%E9%97%AE%E9%A2%98

但是实际上我测试了 class 写法 直接 在 onInput 事件里 setdata 更新 就可以,如果不 setdata 只 return 反而不行

搜到另一个相关的issue #6070

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
F-react Framework - React T-weapp Target - 编译到微信小程序 V-3 Version - 3.x
Projects
None yet
Development

No branches or pull requests

2 participants