代码之家  ›  专栏  ›  技术社区  ›  8-Bit Borges

ReactJS—组件中函数返回的显示值

  •  0
  • 8-Bit Borges  · 技术社区  · 4 年前

    Field.jsx

    class Field extends Component {
      constructor(props) {
        super(props);
      }
    

    players是一个包含如下结构的dict列表:

    [{"name": "Edson", "position": "Forward"}...{...}, {...}]
    

    我创建了这个函数来过滤dict列表,以便根据一个位置显示所有玩家的名字:

    getPlayersByPosition = (players, position) => {
        return players.filter((player) => player.position === 'Forward');
      }
    

    这里我试图直接显示函数返回的第一个播放器'name' <Position> HERE </Position> ,带有:

    render() {
        const { players } = this.props;
        if(players){
          return (
           <div className="back">
              <div className="field-wrapper">
                <Output output={this.props} />
                <div className="row">
                  <Position>
                   {this.getPlayersByPosition(players, 'Forward')[0]}> //does not work
                  </Position>
                  <Position> 
                   {players[1].name} //works
                  </Position>
                </div>
              </div>
            </div>
          );
      }else{
        return null}
      }
    }
    

    在我第一次 <Position>

    enter image description here

    在第二次打印值时:

    enter image description here


    0 回复  |  直到 4 年前
        1
  •  2
  •   Mohammad Faisal    4 年前

    在React中,对象作为子对象无效。所以当你试图渲染

    {this.getPlayersByPosition(players, 'Forward')[0]}
    

    它从过滤数组返回第一个对象。

    {this.getPlayersByPosition(players, 'Forward')[0].name}
    

    应该有用的