有没有办法将道具传递给反应中包含的组件?
Is there a way to pass props to a contained component in react?
如果我有这样定义的组件:
export default class LinkContainer extends React.Component {
render() {
return (
<div>
<a href={this.props.baselink}>
<h3>{this.props.title}</h3>
</a>
{this.props.children}
</div>
)
}
}
有没有办法将 this.props.baselink
传递给 this.props.children
中的所有组件?
您可以通过使用 cloneElement. Map over your children and clone each one, passing a second argument to the cloneElement, which will act as props. isValidElement 来执行此操作,以防您有无法克隆的子节点,例如文本节点。
export default class LinkContainer extends React.Component {
render() {
return (
<div>
<a href={this.props.baselink}>
<h3>{this.props.title}</h3>
</a>
{Children.map(this.props.children, (child) => {
if (!isValidElement(child)) return child;
return cloneElement(child, { baselink: this.props.baselink });
})}
</div>
);
}
}
如果我有这样定义的组件:
export default class LinkContainer extends React.Component {
render() {
return (
<div>
<a href={this.props.baselink}>
<h3>{this.props.title}</h3>
</a>
{this.props.children}
</div>
)
}
}
有没有办法将 this.props.baselink
传递给 this.props.children
中的所有组件?
您可以通过使用 cloneElement. Map over your children and clone each one, passing a second argument to the cloneElement, which will act as props. isValidElement 来执行此操作,以防您有无法克隆的子节点,例如文本节点。
export default class LinkContainer extends React.Component {
render() {
return (
<div>
<a href={this.props.baselink}>
<h3>{this.props.title}</h3>
</a>
{Children.map(this.props.children, (child) => {
if (!isValidElement(child)) return child;
return cloneElement(child, { baselink: this.props.baselink });
})}
</div>
);
}
}