如何以编程方式用React填充输入字段的值? [英] How do I programatically fill input field value with React?

查看:32
本文介绍了如何以编程方式用React填充输入字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些输入字段的模态.使用用户在输入字段中使用 onChange 函数作为

I have a modal with some input fields. I can easily pass the data automatically with the user typing an input, using onChange function in the input field, as

<Input onChange={this.props.store.handleCategoryChange} type="text" />

和..(虽然使用mobx商店,但不宜使用)

and .. (Using a mobx store, irellevant though)

@observable categoryValue;
@action handleCategoryChange = (e, data) => {
    this.categoryValue = data.value;
    e.preventDefault();
};

但是,我想添加一个功能,用户可以在其中使用应用程序中其他位置的信息来预填充此功能.我有数据可以预填充输入字段,但是我想不知道如何在没有用户执行的情况下以编程方式实际输入它?

However, I want to add a function where the user can pre-fill this with information elsewhere in the application. I have the data to pre-fill the input fields with, but I can't figure out how do actually input it programatically, without the user doing it?

我需要调用上面的 handleCategoryChange 函数.但是我的变量等于 data.value ..这就带来了一个问题!我自己无法调用此功能,因为我将没有事件 e 或称为 data.value 的值,因为我将只是"传递一个变量本身.

I need to invoke the above handleCategoryChange function. But my variable would be equal to data.value .. Which presents a problem! Invoking this function by myself isn't possible, because I won't have the event e nor a value called data.value as I will "just" pass in a variable by itself.

在React中使用其他变量自动以编程方式填充输入字段的正确方法是什么?我需要以某种方式调用 onChange 函数,但是输入值将有所不同.

What's the right way to programatically fill an input field automatically in React, using variables elsewhere? I need to invoke the onChange function somehow, but the input values will be different..

推荐答案

使用受控组件,在这种情况下,请定义 input元素 value 属性,如下所示:

Use controlled component for this situation, define a value property of input element like this:

<Input value={variable_name} ....

无论何时更新该变量,该值都会自动填充到输入元素中.

Whenever you will update that variable, automatically that value will get populated in input element.

现在,您可以通过为 variable_name 分配一个值来填充一些默认值,并且用户可以通过 onChange 函数更新该值.

Now you can populate some default value by assigning a value to variable_name and user can update that value by onChange function.

根据 DOC :

一个输入表单元素,其值由React通过这种方式控制被称为受控组件".

An input form element whose value is controlled by React in this way is called a "controlled component".

这篇关于如何以编程方式用React填充输入字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆