onMouseOver和onMouseOut切换输入和div,并更改div的值

时间:2018-11-02 13:38:21

标签: javascript reactjs

我是新来的反应者。当我将value悬停在value上时,我要达到的目标如下所示,并且可以更改输入字段中的值。对我来说,编写纯JavaScript很容易,但是我想在reactjs中实现它并想学习。

这个想法是,隐藏值span tag并在将其悬停时将其替换为带有该值的输入。

我想知道如何在<span className="value"><input type="text" />时切换onMouseOveronMouseOut

enter image description here

import React, { Component } from "react";

class ChangeValue extends Component {
  state = {
    text: ""
  };

  onMouseOver = e => {
    // what should be here? 
  };

  onMouseOut = e => {
    this.setState({
      text: ""
    });
  };

  render() {
    const { text } = this.state;
    return (
      <div className="inputsValue">
        <span className="property">Name</span> :{" "}
        <span className="value">Value</span>
        <input type="text" />
      </div>
    );
  }
}

export default ChangeValue;

1 个答案:

答案 0 :(得分:1)

您可以这样做

import React, { Component } from "react";

class ChangeValue extends Component {
  state = {
    text: "",
    isEditable: false
  };

  onMouseOver = e => {

    this.setState({
       isEditable: true,
       text: e.target.value
    })
  };

  onMouseOut = e => {
    this.setState({
      isEditable: false
    });
  };

  render() {
    const { text } = this.state;
    return (
      <div className="inputsValue">
        { this.state.isEditable ?
             <input type="text" value={this.state.text} onMouseOut={(e) => this.onMouseOut(e)}/>
          :
             <div>
               <span className="property">Name</span> :{" "}
               <span className="value" onMouseOver={(e) => this.onMouseOver(e)}>{this.state.text}</span>
             </div>
      </div>
    );
  }
}

export default ChangeValue;