1. 跨組件向子組件傳值的新方案
通過context可以實現(xiàn)
//根組件
class MessageList extends React.Component {
getChildContext() {
return {color: "purple",text: "item text"};
}
render() {
const children = this.props.messages.map((message) =>
<Message text={message.text} />
);
return <div>{children}</div>;
}
}
MessageList.childContextTypes = {
color: React.PropTypes.string
text: React.PropTypes.string
};
//中間組件
class Message extends React.Component {
render() {
return (
<div>
<MessageItem />
<Button>Delete</Button>
</div>
);
}
}
//孫組件(接收組件)
class MessageItem extends React.Component {
render() {
return (
<div>
{this.props.text}
</div>
);
}
}
MessageItem.contextTypes = {
text: React.PropTypes.string
};
class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
color: React.PropTypes.string
};
2. 克隆子組件
- 用途
可以給子組件包裹props 比如包裹一個權(quán)限配置等等 - 注意點
- 使用方式
React.Children.map(this.props.children, (child) => React.cloneElement(child, {
msg: '新添加的props數(shù)據(jù)'
...
...
}))
3. 子組件children的相關(guān)操作
-
React.Children.map
遍歷子元素 并返回數(shù)組
object React.Children.map(object children, function fn [, object context])
使用方法:
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})
-
React.Children.forEach
遍歷子元素 并返回數(shù)組
React.Children.forEach(object children, function fn [, object context])
-
React.Children.count
獲取子元素的個數(shù)
React.Children.count(object children)
-
React.Children.only
返回 children 中 僅有的子級。否則拋出異常腕柜。
console.log(React.Children.only(this.props.children[0]));
//輸出對象this.props.children[0]