简体   繁体   中英

Dynamically Created Elements in React - How to have control?

This is a more general question. I need an idea to handle a problem, so I won't give you specific code.

I have a list of items, that are output through a map function. Basically all is good. But I want to embed a component, that would show an input to rename that item.

The idea is that someone clicks on some button, that triggers rename handler, and there is an input there to rename that item.

So, the renaming component works, the only thing that I stuck with is this:

in very general terms the code is this

list.map(item => <li key={item.id}>{item.name} <Rename inputValue={this.state.value} inputHandler={this.inputHandler} /></li>)

How to make this rename show up only when then the trigger is clicked only for that item that was clicked to be renamed ? The thing also is, that this input would be bound to a state, and there would be a handler to change that state. And that means, that every input would have the same state and same handler.

So, I hope I was able to describe a problem, how generally things like these would be solved in react?

That is pretty easy to realize in react.

You just need to keep the state in the component.

I show you a very simple mockup:

class Item extends React.Component {
  constructor(props) {
    super(props);
    this.state ={
      showInput: false,
      value: props.value
    }
  }

  triggerClick() {
    this.setState({showInput: true});
  }

  handleChange(value) {
    // do update value
  }

  render() {
    const {value, showInput} = this.state;
    return (
      <div>
        <button onClick={this.triggerClick}>show input</button>
        {showInput ?
          <input type="text" value={value} onChange={this.handleChange}/>
        : null}
        <p>{value}</p>
      </div>
    );
  }
}

And then use what you mention map method to build it.

list.map(item => <Item value={item.value}/>)

It would work as you need.

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