的意义是什么
{...this.props}
我正在尝试这样使用它
<div {...this.props}> Content Here </div>
的意义是什么
{...this.props}
我正在尝试这样使用它
<div {...this.props}> Content Here </div>
它被称为传播属性,其目的是使props的传递更容易。
假设您有一个接受 N 个属性的组件。如果数量增加,将这些传递下去可能会变得乏味和笨拙。
<Component x={} y={} z={} />
因此,您可以这样做,将它们包装在一个对象中并使用扩展符号
var props = { x: 1, y: 1, z:1 };
<Component {...props} />
这会将它解压到组件上的 props 中,即,您“永远不会”{... props}
在render()
函数内部使用,只有当您将 props 传递给另一个组件时。像往常一样使用你解开的propsthis.props.x
。
它是 ES6Spread_operator
和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');
正如你在上面看到的,它将所有的 props 传递给div
.
它是 ES-6 特性。这意味着你提取了props的所有属性
div.{... }
运算符用于提取对象的属性。
您将在子组件中使用 props
例如
如果你现在的组件props是
{
booking: 4,
isDisable: false
}
你可以在你的孩子组件中使用这个props
<div {...this.props}> ... </div>
在您的子组件中,您将收到所有父props。