无法在React js中使用console.log打印属性

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

我想打印从父组件GroceryListItem传入我的组件GroceryList的道具

我的GroceryList代码:

    class GroceryList extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          groceries: [ { name: "Apples"}, {name: "Orange"}, {name : "Banana"} ]
        };
      }

    render() {
        const element = [];
        for(var index = 0; index < this.state.groceries.length; index++) {
           element.push(<ul><GroceryListItem grocery={this.state.groceries[index]} /></ul>);
        }

        return (
         <div>
           {element}
         </div>
    );
  }
}

我的GroceryListItem代码:

class GroceryListItem extends React.Component {

 constructor(props) {
    super(props);

  }

render() {
    // I want to print the props passed here, but below code is not printing it
    console.log("Hi from GroceryListItem " + this.props.grocery); 

    return (
        <li>
          {this.props.grocery}
        </li>
    );
  }
}

控制台打印:

嗨,来自GroceryListItem [对象对象]

控制台显示[object Object],但不显示Apples, Orange, Banana之类的确切值。如何从props

打印所有值
reactjs react-props react-component
1个回答
3
投票

您需要访问对象的name属性

class GroceryListItem extends React.Component {

 constructor(props) {
    super(props);

  }

render() {
    console.log("Hi from GroceryListItem " + this.props.grocery.name); 
    return (
        <li>
          {this.props.grocery.name}
        </li>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.