簡體   English   中英

將道具傳遞給子組件的問題

[英]Problem with passing props to child component

我有ProductList組件

import Title from "./Title";

class ProductList extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return <Title name="Our" title="Products" />;
  }
}

Title組件,它被導出然后在ProductList組件中使用。

class Title extends Component {
  constructor(title, name) {
    super();
    this.title = title;
    this.name = name;
  }
  render() {
    return (
      <div className="product-title">
        {this.name} <strong>{this.title}</strong>
      </div>
    );
  }
}

但我無法呈現titlename

此外,還有一個問題如果我將基於title的組件寫入基於name的組件,我們需要這樣做function Title({ name, title })為什么需要括號?

propsthis.props中可用於基於 class 的組件。 你在這里不需要constructor

class Title extends Component {
  render() {
    const {name, title } = this.props
    return (
      <div className="product-title">
        {name} <strong>{title}</strong>
      </div>
    );
  }
}

如果我將基於 class 的組件寫入基於 function 的組件,我們需要這樣做function Title({ name, title })為什么我們需要括號來包裹?

這是一種稱為解構賦值的模式,它可以將 arrays 中的值或對象的屬性解壓縮到不同的變量中

您可以將object作為參數傳遞,並且只能在函數體內或直接在聲明中解構它

const user = {name: 'John', surname: 'Doe'}
logUser(user)

const logUser = user =>{
   const { name, surname } = user

   console.log(name, surname)
}

相當於

const logUser = ({ name, surname }) => console.log(name, user)

由於功能組件接收的唯一參數是props ,因此您可以像傳遞它一樣

<Child foo='bar' />

並直接從props object 中解構參數

const Child = ({ foo }) => <span> {foo} </span>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM