【问题标题】:In React, how do I update a text form field in which the backing state is an array?在 React 中,如何更新支持状态为数组的文本表单字段?
【发布时间】:2020-08-12 10:05:59
【问题描述】:

我正在创建一个 React 16.13.0 应用程序并尝试设计一个表单,该表单可以提交到接受数据的端点......

{
        "name": "Test 8899",
        "types": [
            {"name": "Library"}
        ],
        "address": {
            "formatted": "222 W. Merchandise Mart Plaza, Suite 1212",
            "locality": {
                "name": "Chicago",
                "postal_code": "60654",
                "state": 19313
            }
        },
        ...

请注意,“类型”输入是一个项目数组。所以我创建了一个 FormContainer 组件,其状态如下...

class FormContainer extends Component {
  static DEFAULT_COUNTRY = 484
  static REACT_APP_PROXY = process.env.REACT_APP_PROXY

  constructor(props) {
    super(props);

    this.state = {
      countries: [],
      provinces: [],
      errors: [],
      newCoop: {
        name: '',
        types: [{
          name: ''
        }],

然后是类型组件本身的“handleTypeChange”函数...

  handleTypeChange(e) {
    let self=this
    let value = e.target.value;
    let name = e.target.name;
    //update State
    this.setState({newCoop: types[0].name = value}); 
  }

...
            <Input inputType={'text'}
               title= {'Type'} 
               name= {'types[0].name'}
               value={this.state.newCoop.types[0].name} 
               placeholder = {'Enter cooperative type'}
               handleChange = {this.handleTypeChange}

               /> {/* Type of the cooperative */}

但是,当我开始在字段中输入时,我立即收到错误

Line 96:29:  'types' is not defined  no-undef

设置句柄输入更改功能的正确方法是什么,以便我可以在我的状态下正确记录用户输入?

【问题讨论】:

  • types数组可以有多个对象还是只有1个对象?
  • 如果您将我们指向Line 96:29 的代码会有所帮助。同时,你能不能“解开”这个name= {'types[0].name'}?这通常应该评估为某个值。此外,由于数据的复杂性,您可能希望使用 spread 运算符。
  • 你真的需要传递 value 属性吗?输入应该显示没有它的文本

标签: arrays reactjs forms components


【解决方案1】:

TLDR:当您将其作为道具传递时,handleTypeChange 方法将无法访问类组件 (this)。

在类组件中将类方法作为道具传递时处理“this”的两种方法:

将“this”绑定到构造函数中的方法(handleTypeChange)

constructor (props) {
  super();
  ...
  this.handleTypeChange = this.handleTypeChange.bind(this);
}

或将箭头函数传递给handleChange prop,如下所示:

handleChange = {(e) => this.handleChange(e)}

更新:

要合并handleTypeChange 中的状态,您可以这样做

  handleInput(e) {
    this.setState({
      // merge the rest of the state, then spread the love here
      newCoop: { ...this.state.newCoop, types: [{ name: e.target.value }] }
    });
  }

查看我的codesandbox 以获得更完整的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-02
    • 2020-05-28
    • 1970-01-01
    • 2020-05-11
    • 2021-01-14
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多