簡體   English   中英

在React Js中單擊加號后如何添加新的輸入字段

[英]how to add new input field after click plus icon in React Js

我想每次單擊加號圖標時都添加一個新輸入,但它總是將其添加到末尾。 我希望將其添加到單擊的項目旁邊。

這是我使用過的React代碼。

 const Input = props => ( <div className="answer-choice"> <input type="text" className="form-control" name={props.index} /> <div className="answer-choice-action"> <i onClick={props.addInput}>add</i> <i>Remove</i> </div> </div> ); class TodoApp extends React.Component { constructor(props) { super(props); this.state = { choices: [Input] }; } addInput = index => { this.setState(prevState => ({ choices: update(prevState.choices, { $splice: [[index, 0, Input]] }) })); }; render() { return ( <div> {this.state.choices.map((Element, index) => { return ( <Element key={index} addInput={() => { this.addInput(index); }} index={index} /> ); })} </div> ); } } ReactDOM.render(<TodoApp />, document.querySelector("#app")); 
 <div id="app"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

我必須承認這會使我陷入困境,但是反應如何處理key道具存在問題。 當您使用索引作為鍵時,它將不起作用。 但是,如果您確保即使列表更改輸入也將始終被分配相同的鍵 ,它將按預期工作:

const Input = props => (
  <div className="answer-choice">
    <input type="text" className="form-control" name={props.index} />
    <div className="answer-choice-action">
      <i onClick={props.addInput}>add </i>
      <i>Remove</i>
    </div>
  </div>
);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      choices: [],
      nrOfElements: 0
    };
  }

  addInput = index => {
    this.setState(prevState => {
      const choicesCopy = [...prevState.choices];
      choicesCopy.splice(index, 0, `input_${prevState.nrOfElements}`);
      return {
        choices: choicesCopy,
        nrOfElements: prevState.nrOfElements + 1
      };
    });
  };

  componentDidMount() {
    this.addInput(0);
  }

  render() {
    return (
      <div>
        {this.state.choices.map((name, index) => {
          return (
            <Input
              key={name}
              addInput={() => {
                this.addInput(index);
              }}
              index={index}
            />
          );
        })}
      </div>
    );
  }
}

來自文檔的一些參考:

應該為數組內部的元素賦予鍵,以使元素具有穩定的身份 ... ... 如果項目的順序可能改變,我們不建議對鍵使用索引 這可能會對性能產生負面影響,並可能導致組件狀態出現問題。

暫無
暫無

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

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