简体   繁体   English

当输入值来自“未声明”提供者时,光标跳转到结束

[英]Cursor jumps to end when input value comes from “unstated” provider

I have currently facing a problem with provider (from unstated lib) and input. 我目前面临提供者(来自未说明的lib)和输入的问题。 In our project, we have to share inputs values between several components, so we have created a provider (with unstated lib) that contains the values. 在我们的项目中,我们必须在几个组件之间共享输入值,因此我们创建了一个包含值的提供程序(带有未声明的lib)。 The values are passing as props into SearchForm component thanks to withSearchFields function. 由于withSearchFields函数,这些值作为props传递给SearchForm组件。

What is the current behavior? 目前的行为是什么? The problem is, each time we want to update the value at any position, the cursor jumps to the end of the input. 问题是,每次我们想要更新任何位置的值时,光标都会跳转到输入的末尾。 For example, I have "aaaa", if I type many "b" on the middle of the input in order to have "aabbbbbaa", the result will be "aabaabbbb" 例如,我有“aaaa”,如果我在输入的中间键入许多“b”以便拥有“aabbbbbaa”,结果将是“aabaabbbb”

What is the expected behavior ? 预期的行为是什么? The cursor doesn't go to the end. 光标不会结束。

I have simplified our code and add it in CodeSandbox : https://codesandbox.io/s/n2w9xv090 我简化了代码并将其添加到CodeSandbox中: https ://codesandbox.io/s/n2w9xv090

Which versions of React ? 哪个版本的React? 16.8.6 16.8.6

Thank you for your help ! 谢谢您的帮助 !

You can update unstated state by onBlur . 您可以通过onBlur更新unstated声明的状态。

  1. set a state for Input 为Input设置状态
const [inputValue, setValue] = useState(value);

  <input
    onChange={event => {
    const { target } = event;
      setValue(target.value);
    }}

  1. pass onBlur to Input onBlur传递给Input
  <input
    onChange={event => {
    const { target } = event;
      setValue(target.value);
    }}
    onBlur={onBlur}

  1. update unstated state by onBlur 通过onBlur更新unstated声明的状态
  const handldBlur = event => {
    const { target } = event;
    props.setField(target.name, target.value);
  };

I modified your code, you can test it in CodeSandbox : https://codesandbox.io/s/priceless-kowalevski-2kdyn?fontsize=14 我修改了你的代码,你可以在CodeSandbox中测试它: https ://codesandbox.io/s/priceless-kowalevski-2kdyn fontize = 14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM