var ProfilePic = React.createClass({
render: function() {
return (
<img src={'http://graph.facebook.com/' + this.props.username + '/picture'} />
);
}
});
var ProfileLink = React.createClass({
render: function() {
return (
<a href={'http://www.facebook.com/' + this.props.username}>
{this.props.username}
</a>
);
}
});
var Avatar = React.createClass({
render: function() {
return (
<div>
<ProfilePic username={this.props.username} />
<ProfileLink username={this.props.username} />
</div>
);
}
});
ReactDOM.render(
<Avatar username="pwh" />,
document.body
);
var MyCheckbox = React.createClass({
handleChange: function(event){
var checked = event.target.checked;
this.props.onChanged(checked);
},
render: function(){
return (
<label htmlFor="check1">
<input type="checkbox" id="check1" name="" onChange={this.handleChange}/>
選我
</label>
);
}
});
var MyForm = React.createClass({
handleChange: function(value){
if(value){
console.log('被選中了');
}else{
console.log('取消選中');
}
},
render: function(){
return (
<div className="form-group">
<MyCheckbox onChanged={this.handleChange}/>
</div>
);
}
});
ReactDOM.render(
<MyForm />,
document.body
);
var Parent = React.createClass({
render: function(){
return (
<div>
{this.props.children}
</div>
);
}
});
ReactDOM.render(
<Parent><p>123</p></Parent>,
document.body
);
//渲染結(jié)果
<div>
<p>123</p>
</div>
不過,我們可以通過 React.Children 工具類來操作,就不需考慮這些了。
React.Children工具類共有四個方法:
React.Children.map、React.Children.forEach、React.Children.count、React.Children.only
(1)React.Children.map
React.Children.map(object children, funciton fn[,object context])
在每一個直接子級(包含在 children 參數(shù)中的)上調(diào)用 fn 函數(shù),此函數(shù)中的 this 指向 上下文。如果 children 是一個內(nèi)嵌的對象或者數(shù)組,它將被遍歷:不會傳入容器對象到 fn 中。如果 children 參數(shù)是 null 或者 undefined,那么返回 null 或者 undefined 而不是一個空對象。
var Parent = React.createClass({
render: function(){
return (
<div>
{
React.Children.map(this.props.children,function(item,i){
return item;
})
}
</div>
);
}
});
ReactDOM.render(
<Parent>
<p>1</p>
<p>2</p>
</Parent>,
document.body
);
//渲染結(jié)果
<div>
<p>1</p>
<p>2</p>
</div>
(2)React.Children.forEach
React.Children.forEach(object children, function fn [, object context])
類似于 React.Children.map(),但是不返回對象。
(3)React.Children.count
React.Children.count(object children)
返回 children 當(dāng)中的組件總數(shù),和傳遞給 map 或者 forEach 的回調(diào)函數(shù)的調(diào)用次數(shù)一致。
(4)React.Children.only
React.Children.only(object children)
返回 children 中僅有的子級。否則拋出異常。這里僅有的子級,only方法接受的參數(shù)只能是一個對象,不能是多個對象(數(shù)組)。
總結(jié)
更多建議: