簡體   English   中英

如何更新REACTJS中由數組映射呈現的輸入文本

[英]how to update input text which is render by array map in REACTJS

const data = [
  {
    title: "Hello World",
    company: [
      "Google",
      "Apple",
      "Facebook"
    ]
  }
];

class App extends React.Component {
  render() {
    return (
      <ul>
        {data[0].company.map((item, index) => (
          <input type="text" key={index} value={item}></input>
        ))}
      </ul>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));

它完美地呈現,但是當我嘗試編輯它而不是編輯文本時。 (不可編輯),並且如果我向空白區域值相同的數組中再添加一個輸入,它也將無法正常工作(無法更新)。

您應該為此使用狀態受控組件 我強烈建議您實際閱讀React的主要概念,這些主要概念會在其網站的右側顯示,因為這將使您的開發過程更加輕松。

要將受控組件原理應用於當前代碼,您需要將onChange事件綁定到您的輸入:

class App extends React.Component {
  state = {
    title: "Hello World",
    companies: [
      "Google",
      "Apple",
      "Facebook"
    ],
  };

  updateCompany(newName, index) {
    const { companies } = this.state;
    const newCompanies = [...companies];
    newCompanies[index] = newName;
    this.setState({ companies: newCompanies });
  }

  render() {
    const { companies } = this.state;
    return (
      <ul>
        {companies.map((item, index) => (
          <input type="text" key={index} value={item} onChange={(e) => this.updateCompany(e.target.value, index)}></input>
        ))}
      </ul>
    );
  }
}

嘗試以下代碼:

const data = [   {
    title: "Hello World",
    company: [
      "Google",
      "Apple",
      "Facebook"
    ]  
    } 
];

class App extends React.Component {   
  handleChange = (e) => {
    const target = e.target;
    const value = target.value;
    const name = target.name;
    data[0].company[+name] = value
  }

  render() {
    return (
      <ul>
        {data[0].company.map((item, index) => (
          <input type="text" onchange={this.handleChange} name={""+index} key={index} value={item}></input>
        ))}
      </ul>
    );   
  } 
}

ReactDOM.render(<App />, document.getElementById("app"));

我將索引轉換為輸入名稱,並聽取輸入上的更改,然后將索引轉換為整數以替換數組中的值

嘗試以下方法:)

class App extends React.Component {
  state = {
    companies: data[0].company,
  };

  updateText = (e, index) => {
    const companies = [...this.state.companies];
    companies[index] = e.target.value

    this.setState({ companies });
  }

  render() {
    return (
      <ul>
        {this.state.companies.map((item, index) => (
          <input
            type="text"
            value={item}
            onChange={(e) => this.updateText(e, index)}
          />
        ))}
      </ul>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM