的意义是什么
{...this.props}
Run Code Online (Sandbox Code Playgroud)
我试图像这样使用它
<div {...this.props}> Content Here </div>
Run Code Online (Sandbox Code Playgroud)
Hen*_*son 173
它被称为传播属性,其目的是使道具的传递更容易.
让我们假设您有一个接受N个属性的组件.如果数量增加,将这些传递下来可能是乏味和笨拙的.
<Component x={} y={} z={} />
Run Code Online (Sandbox Code Playgroud)
因此,你这样做,将它们包装在一个对象中并使用扩散符号
var props = { x: 1, y: 1, z:1 };
<Component {...props} />
Run Code Online (Sandbox Code Playgroud)
它会将它解压缩到你组件的道具上,也就是说,只有当你将道具传递给另一个组件时,你才"永远" {... props}
在你的render()
功能中使用.正常使用解压缩的道具this.props.x
.
小智 16
这是ES6 Spread_operator
和Destructuring_assignment
.
<div {...this.props}>
Content Here
</div>
Run Code Online (Sandbox Code Playgroud)
它等于类组件:
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
);
Run Code Online (Sandbox Code Playgroud)
功能组件
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
);
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请查看以下链接:
https://babeljs.io/docs/plugins/transform-object-rest-spread/
https://github.com/gildata/RAIO/issues/136#issuecomment-327361743
https://facebook.github.io/react/docs/components-and-props.html
归档时间: |
|
查看次数: |
79479 次 |
最近记录: |