如何在React中创建一个编辑按钮?

时间:2019-03-13 18:32:39

标签: reactjs button edit

我对React还是很陌生,因此我们将不胜感激!

我想做的是为我的代码创建一个编辑按钮,该按钮使用户可以编辑人的出生年份及其家乡。我希望在按下编辑按钮时将文本显示为文本框,以便用户可以更改它,然后以某种方式保存它。这是我的代码:

class Card extends Component {

    render() {
      const {imgSrc, cardName, birthYear, onEdit} = this.props;
      return (
        <div className='card'>
          <div className='card-content'>
            <div className='card-name'>{cardName}</div>
                <img src={`http://localhost:3008/${imgSrc}`} alt='profile'/>
              <p>
                  <span>Birthday:</span>
                  <span className='birth-year'>{birthYear}</span>
              </p>
              <p>

                  <span>Homeworld:</span>
                  <span className='home-world'>Earth</span>
                  </p>
                <div align='center'>
                <button>Edit</button>
              </div>
            </div>
         </div>

2 个答案:

答案 0 :(得分:0)

您将不得不根据传入的道具设置setState。然后在您的表单中,您需要执行

之类的操作
<input type='text' defaultValue={this.state.user.birthday} />

答案 1 :(得分:0)

您可以具有内部editing状态,基于该状态,组件将使用默认值作为该字段的当前值的输入字段或<span>来呈现。当您按下编辑按钮时,它将翻转为true。您还必须有条件地呈现一个更新/保存按钮,并在单击保存时更新值。这是一般的想法。

class Card extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editing: false
    };
    this.newbirthYear = "";
    this.newHomeWorld = "";
  }

  render() {
    const { imgSrc, cardName, birthYear, homeWorld, onEdit } = this.props;
    return (
      <div className="card">
        <div className="card-content">
          <div className="card-name">{cardName}</div>
          <img src={`http://localhost:3008/${imgSrc}`} alt="profile" />
          <p>
            <span>Birthday:</span>
            {this.state.editing ? (
              <span className="birth-year">{birthYear}</span>
            ) : (
              <input
                type="text"
                defaultValue={birthYear}
                ref={node => {
                  this.newbirthYear = node;
                }}
              />
            )}
          </p>
          <p>
            <span>Homeworld:</span>
            {this.state.editing ? (
              <span className="home-world">{homeWorld}</span>
            ) : (
              <input
                type="text"
                defaultValue={homeWorld}
                ref={node => {
                  this.newHomeWorld = node;
                }}
              />
            )}
          </p>
          <div align="center">
            <button
              onClick={() => {
                this.setState({ editing: true });
              }}
            >
              Edit
            </button>
          </div>
        </div>
      </div>
    );
  }
}

希望这会有所帮助!

相关问题