[React] Spread Component Props in JSX with React

本文介绍如何使用JSX的展开语法来简化React组件属性(props)的传递过程,避免重复书写相同的属性名,适用于纯组件及类组件。

You often find duplication between the name of a prop and a variable you will assign to the prop. JSX allows you to spread an object containing your named props into your Component which enables you to avoid the repetition of matching prop names and variable names. This lessons covers spreading JSX component props in both pure components and class components.

 

We have code:

import React from "react";
import { render } from "react-dom";

const Demo = ({ greeting, name }) => (
  <h2>
    {greeting}, {name}
  </h2>
);

const greeting = "hello";
const name = "John";

const App = () => <Demo greeting={greeting} name={name} />;

render(<App />, document.getElementById("root"));

 

We can simply the code:

const App = () => <Demo {...{greeting, name}}  />;

or

const App = () => Demo({greeting, name})

 

But if we using Class Component instead of functional component like:

class Demo extends React.Component {
  render() {
    return (
      <h2>
        {this.props.greeting}, {this.props.name}
      </h2>
    )
  }
}

Then we have to use JSX approach or:

const App = () => React.createElement(Demo, {greeting, name});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值