简体   繁体   中英

How to create input field dynamically in ReactJS?

i have a project, and i would want to know how i can to create a inpult field after an event of onClick?

I have that code:

 onSubmitCell = event => { const newCell = prompt("Please with new URL:"); const personCurrent = event.target.value; axios.patch(`http://localhost:3004/employee/${personCurrent}`, { cellphone: newCell }) .then(response => { console.log(response.data); }) .catch(error => { console.log(error); }); } 

What it do? It get the value of alert and do the Patch to update the attribute of the object.

What do i want ? Instead of open an alert , i would want that appeared an input , and i get the value of this input and did the Patch .

Someone would can help me ? Please?

You can use state for this I am sharing you basic code so you can Implement.

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isPatch: false
    };
  }

  onSubmitCell = event => {
    const newCell = prompt("Please with new URL:");
    this.setState({
      isPatch: true
    });
    const personCurrent = event.target.value;
    axios
      .patch(`http://localhost:3004/employee/${personCurrent}`, {
        cellphone: newCell
      })
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  };

  onChange = e => {
    this.setState({
      patchValue: e.target.value
    });
  };

  render() {
    return (
      <div>
        {" "}
        {this.state.isPatch && (
          <input
            type="text"
            onchange={this.onChange}
            value={this.state.patchValue}
          />
        )}{" "}
      </div>
    );
  }
}

You can do it using a state.

eg

constructor(){
   super();
   this.state={
       showInput: false
   }
}
render(){
    return(
        <div>
            {this.state.showInput && <input />}
        </div>
    )
}

Instead of alert you can change the state to true . It'll display the input .

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