在react中,会看到{...this.props}的代码,不知道是什么意思,现在记录一下。
{...this.props}是props所提供的语法糖,可以将父组件的所有属性复制给子组件
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>...this.props</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="xpf"></div>
<script type="text/babel">
class Xpf extends React.Component {
render() {
return (
<div>
<a {...this.props}>{this.props.name}</a>
</div>
);
}
}
ReactDOM.render(
<Xpf href="https://blog.csdn.net/qq_42720683" name='我只是一个测试'/>,
document.getElementById('xpf')
);
</script>
</body>
</html>
在子组件Xpf中,本来没有href属性,但是父组件有href和name属性,子组件Xpf使用了{...this.props}后,就可以拿到父组件中的href属性,此处即可以跳转到我的博客。
效果如下: