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

问题描述 投票:0回答:2

我对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>
reactjs button edit
2个回答
1
投票

您可以拥有一个内部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>
    );
  }
}

希望这可以帮助 !


0
投票

你将不得不根据传入的道具设置setState。然后在你的表格中你需要做类似的事情

<input type='text' defaultValue={this.state.user.birthday} />
© www.soinside.com 2019 - 2024. All rights reserved.