将对象添加到对象的数组并在React中设置状态

时间:2019-11-22 20:47:42

标签: javascript reactjs

我是React的新手,我想出了一个想法,可以一次学习很多东西。我有这个组件,它的初始状态是一个包含棒球运动员对象的数组,我需要通过输入字段向状态添加新的棒球运动员的名字,然后,一旦添加了棒球运动员,第二个组件就会出现带有输入字段的添加数据。

我该怎么做?

export default class BaseballPlayerList extends React.Component {
  constructor() {
    super();
    this.state = {
      baseBallPlayers: [
        {
          name: "Barry Bonds",
          seasons: [
            {
              year: 1994,
              homeRuns: 37,
              hitting: 0.294
            },
            {
              year: 1996,
              homeRuns: 40,
              hitting: 0.294
            }
          ]
        }
      ]
    };
    this.addPlayer = this.addPlayer.bind(this);
  }
  addPlayer(e) {
    e.preventDefault();
    const newPLayer = {
      baseBallPlayers: this.state.baseBallPlayers.name,
      seasons: []
    };
    console.log(newPLayer);
    this.setState(prevState => ({
      baseBallPlayers: [...prevState.baseBallPlayers, newPlayer]
    }));
  }
  render() {
    return (
      <div>
        <div>
          <ul>
            {this.state.baseBallPlayers.map((player, idx) => (
              <li key={idx}>
                <PlayerSeasonInfo player={player} />
              </li>
            ))}
          </ul>
        </div>

        <input value={this.state.baseBallPlayers.name} />
        <button onClick={this.addPlayer}>AddPlayer</button>
      </div>
    );
  }
}
export default class PlayerSeasonInfo extends Component {
  constructor(props) {
    super(props);
    this.player = this.props.player;
  }
  render() {
    return (
      <div>
        {this.player && (
          <div>
            <span>{this.baseBallPlayers.name}</span>
            <span>
              <input placeholder="year" />
              <input placeholder="homeRuns" />
              <input placeholder="hitting" />
              <button>AddInfo</button>
            </span>
          </div>
        )}
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

这里有一个有效的示例:https://codesandbox.io/s/nervous-yonath-9u2d6

问题在于您在哪里存储新名称以及如何更新整个玩家状态。

希望该示例有所帮助!