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

IT技术 reactjs
2021-03-25 15:48:40

的意义是什么

{...this.props}

我正在尝试这样使用它

 <div {...this.props}> Content Here </div>
5个回答

它被称为传播属性,其目的是使props的传递更容易。

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

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

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

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

这会将它解压到组件上的 props 中,即,您“永远不会”{... props}render()函数内部使用,只有当您将 props 传递给另一个组件时。像往常一样使用你解开的propsthis.props.x

好的 awnser,但是“你“从不”在你的 render() 函数中使用 {... props},只有当你将 props 传递给另一个组件时。是一个非常容易混淆的词组。建议重写为“当您将 props 传递给另一个组件时,您只在 render() 中使用 {... props}。” 为了清楚起见。
2021-05-25 15:48:40
补充一点,将其视为this.transferPropsTo在 React 0.12.x 中已弃用并将在 0.13.x 中删除的替代品会有所帮助。这当然让更高级的用法简单不过翻译作出反应0.11.x的this.transferPropsTo(<Foo />)<Foo {...this.props} />是人们做出这种转变最有用的。
2021-05-27 15:48:40

它是 ES6Spread_operatorDestructuring_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');

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

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

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

您将在子组件中使用 props

例如

如果你现在的组件props是

{
   booking: 4,
   isDisable: false
}

你可以在你的孩子组件中使用这个props

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

在您的子组件中,您将收到所有父props。

很好的答案,但如果您包含有关道具用途的解释,那就更好了。
2021-05-22 15:48:40