1. 跨组件向子组件传值的新方案
通过context可以实现
//根组件
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 比如包裹一个权限配置等等 - 注意点
- 使用方式
React.Children.map(this.props.children, (child) => React.cloneElement(child, {
msg: '新添加的props数据'
...
...
}))
3. 子组件children的相关操作
-
React.Children.map
遍历子元素 并返回数组
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
遍历子元素 并返回数组
React.Children.forEach(object children, function fn [, object context])
-
React.Children.count
获取子元素的个数
React.Children.count(object children)
-
React.Children.only
返回 children 中 仅有的子级。否则抛出异常。
console.log(React.Children.only(this.props.children[0]));
//输出对象this.props.children[0]
网友评论