好的,我曾经对此感到困惑了很长一段时间。因此,我将尽力向您解释:
假设您有一个如下所示的React类:
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
class SingleService extends Component{
render(){
return(
<div class="col-md-4">
<span class="fa-stack fa-4x">
<i class="fas fa-circle fa-stack-2x text-primary"></i>
<i class={`fas ${this.props.icon} fa-stack-1x fa-inverse`}></i>
</span>
<h4 class="service-heading">{this.props.title}</h4>
<p class="text-muted">{this.props.description}</p>
</div>
);
}
}
export default SingleService;
在这里,您可以看到有许多{this.props.variable}。
它们用于在我们将上述类导入另一个类时创建动态值,如下所示:
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
import SingleService from './SingleService';
const services = [
{
title:'E-commerce',
description:'Description text on E-commerce',
icon: 'fa-shopping-cart'
}
];
class Services extends Component{
render(){
return(
<div>
<section class="page-section" id="services">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading text-uppercase">Services</h2>
<h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3>
</div>
</div>
<div class="row text-center">
{/* it's looping through an object, that's why we've used key value pair. */}
{ /*
to write js inside JSX, we use curly braces
here we're using array.map() function.
*/}
{services.map((service, index) => {
// returning our component with props.
// return (<SingleService title={service.title} description={service.description} icon={service.icon} />);
// or, we can write the following
return (<SingleService {...service}/>);
})}
</div>
</div>
</section>
</div>
);
}
}
export default Services;
现在,这里我使用了著名的
return (<SingleService {...SingleService}/>)
但是有一件非常重要的事情,我可以通过编写以下行来避免使用它:
return (<SingleService title={service.title} description={service.description} icon={service.icon} />)
因此,您可以看到在发送返回语句中,我单独指定了所有的props变量并为其分配了值,而在第一个返回语句中,我一次性从SingleService对象中传递了所有的props,这将传递所有的键值对。