存储属于不同选项卡的文本区域的状态

问题描述 投票:0回答:1

我正在尝试创建具有多个选项卡的内容,每个选项卡应包含自己的文本区域,可以在进出每个选项卡时保留其文本。我在渲染函数之前的代码是这样的

const panes = []

for(let i = 0 ; i < inputValue ; i++) {
  const formNumber = "Form: " + (i+1);

  panes.push({
    menuItem: "Form " + (i+1),
    key:{i},
    render: () => (
      <Tab.Pane >
        {i+1}
        <Form.TextArea
          onChange={this.onChange}
          key={i}
        />
      </Tab.Pane>
    )
  });
};

在渲染功能中:

<Tab
  grid={{ paneWidth: 12, tabWidth: 2}}
  menu={{ fluid: true, vertical: true, tabular: 'right' }}
  panes={panes} 
/>

更改选项卡时,在选项卡窗格内呈现的for循环中的i值仍然正确,但文本区域中的信息将丢失。我尝试使用本地状态下面的代码,然后使用onChange函数进行更新

this.state = {
  forms: [{
    formNumber: 1,
    formText: ''
  }]
}

但是在将信息插入表单状态中的正确列表项时遇到了问题。我也试过创建一个不在州内的列表

this.form_text = []

然后插入文本并将表单文本区域的值分配给它,但这似乎是错误的方法

javascript reactjs state semantic-ui-react
1个回答
1
投票

i添加到onChange参数:

onChange={e => this.onChange(e, i)}

这样您可以在状态中更新正确的表单:

onChange = (e, i) => {
  this.setState({
    forms: this.state.forms.map(it => {
      if (it.formNumber !== i) return it; // keep other forms as is

      return { formNumber: i, formText: e.target.value };
    })
  });
};
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.