将道具传递给子组件的问题

Bas*_*nda 1 javascript reactjs

我有ProductList组件

import Title from "./Title";

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

以及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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我不能渲染titlename

此外,一个额外的问题,如果我写的是基于类的组件功能基于组件我们需要做的是这样function Title({ name, title }),为什么我们需要括号{}来包装name,并title在那里?

Dup*_*cas 5

props在内部可this.props用于基于类的组件。你不需要constructor这里

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

如果我将基于类的组件编写为基于函数的组件,我们需要这样做,function Title({ name, title })为什么我们需要用方括号将名称和标题包装在那里?

这是一种称为解构分配的模式,它可以将数组中的值或对象中的属性解包为不同的变量

您可以传递一个objectas参数,并且只能在函数体内或直接在声明中对其进行解构

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

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

   console.log(name, surname)
}
Run Code Online (Sandbox Code Playgroud)

等于

const logUser = ({ name, surname }) => console.log(name, user)
Run Code Online (Sandbox Code Playgroud)

由于功能组件收到的唯一参数是,props您可以像这样传递它

<Child foo='bar' />
Run Code Online (Sandbox Code Playgroud)

并直接从props对象中解构参数

const Child = ({ foo }) => <span> {foo} </span>
Run Code Online (Sandbox Code Playgroud)