简体   繁体   English

如何使用 React 以编程方式填充输入字段值?

[英]How do I programatically fill input field value with React?

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我可以轻松地在用户键入输入时自动传递数据,在输入字段中使用onChange函数,如

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

and .. (Using a mobx store, irellevant though)和..(使用 mobx 商店,虽然无关紧要)

@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?我有用于预填充输入字段的数据,但我无法弄清楚如何在没有用户执行的情况下以编程方式实际输入它?

I need to invoke the above handleCategoryChange function.我需要调用上面的handleCategoryChange函数。 But my variable would be equal to data.value .. Which presents a problem!但我的变量将等于data.value .. 这提出了一个问题! 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.自己调用这个函数是不可能的,因为我不会有事件e也没有名为data.value的值,因为我将“只是”自己传递一个变量。

What's the right way to programatically fill an input field automatically in React, using variables elsewhere?在 React 中使用其他地方的变量以编程方式自动填充输入字段的正确方法是什么? I need to invoke the onChange function somehow, but the input values will be different..我需要以某种方式调用onChange函数,但输入值会有所不同..

Use controlled component for this situation, define a value property of input element like this: 对于这种情况使用受控组件 ,定义input elementvalue属性,如下所示:

<Input value={variable_name} ....

Whenever you will update that variable, automatically that value will get populated in input element. 每当您更新该变量时,该值将自动填充在input元素中。

Now you can populate some default value by assigning a value to variable_name and user can update that value by onChange function. 现在,您可以通过为variable_name赋值来填充一些默认值,用户可以通过onChange函数更新该值。

As per DOC : 根据DOC

An input form element whose value is controlled by React in this way is called a "controlled component". 以这种方式由React控制其值的输入表单元素称为“受控组件”。

传入value属性进行输入:

<input type="text" value={this.state.value} onChange={(e) => {this.setState({value: e.target.value })}/>

you can use the controlled component and pass the value to it. 您可以使用受控组件并将值传递给它。

<input type="text" value{this.state.value} 
       onChange={()=>  {this.setState({value:e.target.value })}}

Good question. 好问题。 I'm having the same issue, and just found a solution. 我遇到了同样的问题,刚刚找到了解决方案。

The problem is that: 问题是:

  • You can't just use the default state of the modal component to set the initial input value, because the modal renders one time within the parent component (starting off invisible), so the default state of the Modal wont keep up with any changes to the 'pre-filled' info in the store that the inputs within the modal require access to. 你不能只使用模态组件的默认状态来设置初始输入值,因为模态在父组件中呈现一次(从不可见开始),因此模态的默认状态不会跟上任何更改商店中的“预填充”信息,模态中的输入需要访问。
  • You can't use the value attribute of the input to reference some redux store prop, since this is needed to reference the onChange function so the user can make changes to that pre-filled info. 您不能使用输入的value属性来引用某个redux store prop,因为这需要引用onChange函数,以便用户可以更改预先填充的信息。
  • And, you can't use the onChange function to set the initial value, because it is required to update the local state with the users changes - not set an initial value. 并且,您不能使用onChange函数来设置初始值,因为需要使用用户更改来更新本地状态 - 而不是设置初始值。 Anyway, this requires the user to click on something, and you want the modal inputs to be pre-populated before the user does anything as soon as the modal opens... 无论如何,这需要用户点击某些内容,并且您希望在模态打开后用户执行任何操作之前预先填充模态输入...

So. 所以。 What we need is to update these input fields every time the Modal attribute isModalOpen (or whatever you are using) changes. 我们需要的是每次Modal属性isModalOpen(或任何你正在使用的)更改时更新这些输入字段。

(ie, pre-populate the fields when the Modal is opened). (即,在打开模态时预先填充字段)。

Again, note that opening the Modal is not RENDERING the modal, it was already rendered, once, and has sat there being invisible until that isModalOpen attribute changed to true. 再次注意,打开模态不是渲染模态,它已经渲染了一次,并且一直存在,直到那个isModalOpen属性变为true。

The Solution: 解决方案:

Step 1: make a handler function in the Modal component that prefills the inputdata by updating the local state of the Modal component. 步骤1:在Modal组件中创建一个处理函数,该函数通过更新Modal组件的本地状态来预填充输入数据。 Mine looks like this : 我看起来像这样:

handlePreFillModalInputsOnOpen = () => {
    this.setState(() => ({
        orthForm: this.props.matchLexUnit['orthForm'],
        orthVar: this.props.matchLexUnit['orthVar'],
        oldOrthForm: this.props.matchLexUnit['oldOrthForm'],
        oldOrthVar: this.props.matchLexUnit['oldOrthVar'],
        source: this.props.matchLexUnit['source'],
        namedEntityCheck: this.props.matchLexUnit['namedEntityCheck'],
        styleMarkingCheck: this.props.matchLexUnit['styleMarkingCheck'],
        artificialCheck: this.props.matchLexUnit['artificialCheck'],
        error: ''
    }));
};

Step 2: Make that function fire ONLY when the isOpen attribute of the modal changes from false to true. 步骤2:该功能只火时的模态变化 ,从虚假到真实的ISOPEN属性。 (This is the meat of your problem I think). (我认为这是你问题的关键)。 Use the lifecycle method componentDidUpdate . 使用生命周期方法componentDidUpdate This will execute every time the props of the modal change. 这将在每次模态的道具改变时执行。

componentDidUpdate(prevProps) {
    if (this.props.isModalOpen === true && prevProps.isModalOpen === false) {
        this.handlePreFillModalInputsOnOpen();
    }
}

Watch out 小心

  • make sure that you have a conditional in componentDidUpdate, otherwise you can run into infinite-loop/performance issues 确保在componentDidUpdate中有条件,否则可能会遇到无限循环/性能问题
  • if you have the possibility of null values icoming in as the prefilled input info, make a null-check so that they will not be passed into the local state. 如果您有可能将空值作为预填充输入信息,请进行空检查,以便它们不会传递到本地状态。

Hope this helps :) 希望这可以帮助 :)

How to Programmatically Prefill, Fill or Update input fields value in React or useState Hooks?如何在 React 或 useState Hooks 中以编程方式预填充、填充或更新输入字段值?

Firstly - Get and define the data from database首先 - 从数据库中获取和定义数据

const **yourData** = isDataFromDatabase;

or if the data is stored in Redux, then...或者如果数据存储在 Redux 中,那么...

const **yourData** = useSelector(isDataFromDatabase);

Secondly - append it as the default value of a useState hook其次 - 将其附加为 useState 钩子的默认值

const [isDataValue, setIsDataValue] = useState(**yourData**);

Thirdly - create a function to watch and Update the changes made by the user to your data value and set it to the useState hook created above第三 - 创建一个函数来监视和更新用户对您的数据值所做的更改,并将其设置为上面创建的 useState 钩子

/** handles Your Data Value */
const handleDataValue = (text) => {
 setIsDataValue(text);
};

Lastly - in your input tag, use the useState State as the "Value" parameter so it can be updated with the onChange function最后 - 在您的输入标签中,使用 useState State 作为“Value”参数,以便它可以使用 onChange 函数进行更新

<input
 className="css"
 id="myDataInput"
 type="text"
 value={isDataValue}
 placeholder={isDataValue}
 onChange={(e) => handleDataValue(e.target.value)}
/>

Now when you load the component, the prefilled value will be shown and can be updated in the HTML Input field.现在,当您加载组件时,预填充的值将显示并可在 HTML 输入字段中更新。

That's All.就这样。

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

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