javascript - 将 Prop 传递给子组件的问题

标签 javascript reactjs

我有 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

此外,还有一个问题如果我将基于类的组件编写为基于函数的组件,我们需要这样做 function Title({ name, title }) 为什么我们需要括号 {}把 nametitle 包起来?

最佳答案

props 可在 this.props 中用于基于类的组件。这里不需要构造函数

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

If i write that class based component to function based component we need to do it this way function Title({ name, title }) why do we need brackets to wrap name and title there?

这是一个名为 destructuring assignment 的模式这使得将数组中的值或对象中的属性解压缩到不同的变量中成为可能

您可以传递一个对象作为参数,并且只在函数体内或直接在声明中解构它

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对象中解构参数

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

关于javascript - 将 Prop 传递给子组件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58843222/

相关文章:

javascript - 首先使用 webpack 来响应 js 应用程序。用java

reactjs - 是否需要 useMemo 来通过 reactjs 中的上下文 API 管理状态?

javascript - 如何在 JSX for Atom 的 .js 文件中启用 HTML 标签的自动完成?

javascript - 如何在javascript中通过json对象进行映射?

javascript - 如何在javascript中使用luhn算法获取下一个校验位

javascript - this.getDoc() 在 FF 中使用 tinymce 为空

javascript - 为什么我的 redux 存储将属性映射到具有单个属性和值的对象?

javascript - 添加或删除在 Handsontable 中不起作用的列

javascript - Selenium Webdriver JavaScript : Promise seems to not be resolved

javascript - y 轴为时间的图表