Reactjs 中的 {...this.props} 是什么意思

What is the meaning of {...this.props} in Reactjs

是什么意思
{...this.props}

我正在尝试这样使用它

 <div {...this.props}> Content Here </div>

叫做spread attributes,目的是为了让道具的传递更容易。

让我们假设您有一个接受 N 个属性的组件。如果数量增加,将这些向下传递可能会很乏味和笨拙。

<Component x={} y={} z={} />

因此,您改为这样做,将它们包装在一个对象中并使用扩展符号

var props = { x: 1, y: 1, z:1 };
<Component {...props} />

这会将它解压到组件的 props 中,即,您 "never" 在 render() 函数中使用 {... props},只有当您将 props 传递给另一个组件时。正常使用解压后的道具 this.props.x.

这是 ES-6 的特性。这意味着你提取道具的所有属性 div.{... }

运算符用于提取对象的属性。

是 ES6 Spread_operator and Destructuring_assignment

<div {...this.props}>
  Content Here
</div>

等于Class Component

const person = {
    name: "xgqfrms",
    age: 23,
    country: "China"
};

class TestDemo extends React.Component {
    render() {
        const {name, age, country} = {...this.props};
        // const {name, age, country} = this.props;
        return (
          <div>
              <h3> Person Information: </h3>
              <ul>
                <li>name={name}</li>
                <li>age={age}</li>
                <li>country={country}</li>
              </ul>
          </div>
        );
    }
}

ReactDOM.render(
    <TestDemo {...person}/>
    , mountNode
);


Function component

const props = {
    name: "xgqfrms",
    age: 23,
    country: "China"
};

const Test = (props) => {
  return(
    <div
        name={props.name}
        age={props.age}
        country={props.country}>
        Content Here
        <ul>
          <li>name={props.name}</li>
          <li>age={props.age}</li>
          <li>country={props.country}</li>
        </ul>
    </div>
  );
};

ReactDOM.render(
    <div>
        <Test {...props}/>
        <hr/>
        <Test 
            name={props.name}
            age={props.age}
            country={props.country}
        />
    </div>
    , mountNode
);

参考资料

它将编译为:

React.createElement('div', this.props, 'Content Here');

正如你在上面看到的,它将它的所有属性传递给 div

您将在 child 组件中使用道具

例如

如果你现在的组件道具是

{
   booking: 4,
   isDisable: false
}

您可以在您的 child 组件中使用此道具

 <div {...this.props}> ... </div>

在您的 child 组件中,您将收到所有 parent 道具。

我们可以在 nextJS 中传递道具,例如:

            <Component {...{
              props,
              allCount: count?.lenght,
            }} />