Reactjs中{…this.props}的含义是什么

reactjs React.js

梅Jim

2020-03-12

是什么意思

{...this.props}

我正在尝试那样使用它

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

第949篇《Reactjs中{…this.props}的含义是什么》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
神奇启人 2020.03.12

您将在子组件中使用道具

例如

如果您现在的组件道具是

{
   booking: 4,
   isDisable: false
}

你可以在你的孩子电脑里使用这个道具

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

在子组件中,您将收到所有父项道具。

LEYAItachi 2020.03.12

是ES6 Spread_operatorDestructuring_assignment

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

它等于类组件:

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
);

在此处输入图片说明


功能组成

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
);

在此处输入图片说明

有关更多详细信息,请参见以下链接:

null 2020.03.12

这是ES-6的功能。这意味着您可以提取道具的所有属性 div.{... }

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

Tom米亚老丝 2020.03.12

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

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

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

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

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

which will unpack it into the props on your component, i.e., you "never" use {... props} inside your render() function, only when you pass the props down to another component. Use your unpacked props as normal this.props.x.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android