項目中遇到秀撇,瞬間懵逼超棺,這不是我認識的this.props用法啊呵燕!一問才知道棠绘,原來還有這種操作,特此留存,以備后查氧苍!
props常規(guī)用法
props
是react
框架組件化一個重要組成夜矗,this.props
對象的屬性與其組件的屬性是一一對應(yīng)的。舉例如下:
//組件Component:
<Component name="hahahaha",age="23",sex="famale" />
//Component內(nèi)部:
class Component extends React.Component{
render(){
return (
<div>{this.props.name}</div>
)
}
}
export default Component;
//輸出hahahaha
this.props.children用法
this.props.children
表示組件的所有子節(jié)點让虐。
<!DOCTYPE html>
<html>
<head>
<script src="../build/react.js"></script>
<script src="../build/react-dom.js"></script>
<script src="../build/browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
var NotesList = React.createClass({
render: function() {
return (
<ol>
{
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})
}
</ol>
);
}
});
ReactDOM.render(
<NotesList>
<span>hello</span>
<span>world</span>
</NotesList>,
document.getElementById('example')
);
</script>
</body>
</html>
//輸出:
hello
world
這里需要注意的是紊撕,只有當子節(jié)點多余1個時,this.props.children 才是一個數(shù)組澄干,否則是不能用 map 方法的逛揩, 會報錯。