【问题标题】:Not able to print properties with console.log in React js无法在 React js 中使用 console.log 打印属性
【发布时间】:2019-11-19 10:18:47
【问题描述】:

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

我的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]

控制台显示[object Object],但不是Apples, Orange, Banana 等精确值。如何打印来自props的所有值

【问题讨论】:

    标签: reactjs react-props react-component


    【解决方案1】:

    您需要访问对象的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>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 2017-06-29
      • 2020-02-21
      • 2017-09-07
      • 2019-05-04
      • 2011-06-16
      • 1970-01-01
      相关资源
      最近更新 更多