如何在指定值的React组件中包含文本输入? [英] How to include a text input in a React component with its value specified?

查看:44
本文介绍了如何在指定值的React组件中包含文本输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在React组件中包含一个文本输入,其初始值从该组件的props传递:

I need to include a text input in a React component, with its initial value passed from the component's props:

 <input value={this.props.value} type='text'/>

但是输入不可编辑,React抱怨:

But the input is not editable, and React complains:

 Warning: Failed form propType: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field.

所以我添加了一个onChange事件处理程序:

So I add a onChange event handler:

 <input value={this.props.value} type='text' onChange={this.valueChanged} />

我应该在valueChanged处理程序中做什么来更新输入值?我必须使用状态吗?

What should I do in the valueChanged handler to update the input value? Do I have to use state?

推荐答案

请查看表单文档,特别是受控组件.

Have a look at the documentation on forms, specifically controlled components.

处理更改事件的 valueChanged()方法将执行以下操作:

Your valueChanged() method, where the change event is handled, would do something like this:

valueChanged(event) {
  this.setState({
    value: event.target.value //set this.state.value to the input's value
  });
}

这意味着,是的,您的输入值将需要使用状态( this.state.value .)如果要从中填充 this.state.value this.props.value ,您可以在构造函数中执行以下操作:

That means that yes, your input value would need to use state (this.state.value.) If you want this.state.value to be populated from this.props.value, you could do something like this in the constructor:

constructor(props) {
  super(props);
  this.state = {
    value: props.value //passed prop as initial value
  }
  this.valueChanged = this.valueChanged.bind(this);
}

上面的代码最初会将 this.state.value 设置为传递的prop value 的值.然后将state和 onChange 处理程序中的值应用于您的< input> :

The above will initially set this.state.value to the passed prop value's value. Then apply the value from state and the onChange handler to your <input>:

<input value={this.state.value} type="text" onChange={this.valueChanged} />

由于 this.state.value 是当前输入值,并且每次更改该值都会对其进行更新,因此它可以按预期输入.

Since this.state.value is the current input value, and is updated every time that value is changed, it becomes input-able as expected.

这是一个小提琴(感谢安德鲁): http://jsfiddle.net/ow99x7d5/2

Here's a fiddle (thanks, Andrew): http://jsfiddle.net/ow99x7d5/2

这篇关于如何在指定值的React组件中包含文本输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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