简体   繁体   中英

Add in array elements with index from multiple inputs

I'm getting a string with marked characters and replacing them with inputs to let users edit messages . I want to save it with new values and send it back to server. Briefly , Im spliting string by "/" , finding strings with "#" and replacing with inputs. Now I want add in a new array changed values and current indexes from input. But it saves only one value. May be could suggest me another way of doing it. This is challenging task for me .

my fiddle: https://jsfiddle.net/armakarma/d2qyha0w/11/

editModalText() {
    let modalMessage="Hello, my name is /# Ann #/. I'm working for /# IStaff #/, could you please call me back"

    return (
      <div>
        {modalMessage
          .split("/")
          .map((text, idx) =>
            text.includes("#") ? this.replaceCharacter(idx, text) : text,
          )}
      </div>
    )
  }
handleChange(e) {
    let arrayString = []
    arrayString.splice(Number(e.target.name), 0, e.target.value)
    this.setState({ editedArray: arrayString })
    console.log(arrayString)
  }

replaceCharacter(idx, text) {
    let formattedText = text.replace(/#/g, " ")

    return (
      <input
        key={idx}
        name={idx}
        defaultValue={formattedText}
        onChange={e => this.handleChange(e)}
      />
    )
  }

I think you would be better off storing your data in a keyed object rather than in an array.

So, add some default state:

  state = {
    editedData: {}
  }

Then, in your handleChange , set the editedData object to be the last iteration but overrwrite the index key with the latest value like:

  this.setState({ 
    editedData: { ...this.state.editedData, [e.target.name]: e.target.value } 
  })

Then, if you log out that object, you will have something like {1: " Ann adsadasd", 3: " IStaff adasdasdasd"} where each key will correspond to the index in the array of editable data so it would be easy to mutate that back into an array.

This is definitively not a React way of doing things. It is too overly complex for something that React handles very efficiently.

  • You are not utilising state. Changes to state re-render the component so it would update for you easily.
  • You are sending the item inside onClick, adding a lambda function to render, where you should pass a reference and use dataset/value.

The most basic example of how to achieve this for a single item is:

class TodoApp extends React.Component {
  state = {
    name: '',
    company: ''
  };

  renderEditModalText() {
    const { name, company } = this.state;

    return (
      <div>
        Hello, my name is{' '}
        <input name="name" value={name} onChange={this.handleChange} placeholder="enter name" />. I'm
        working for{' '}
        <input name="company" value={company} onChange={this.handleChange} placeholder="enter company name" />,
        could you please call me back
      </div>
    );
  }

  handleChange = e => {
    const { name, value } = e.target;
    this.setState({ [name]: value });
  };

  render() {
    return <div>{this.renderEditModalText()}</div>;
  }
}

ReactDOM.render(<TodoApp />, document.querySelector('#app'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM