[英]React: why doesn't React.addons.cloneWithProps work with Components?
我不知道这是错误还是解决方法,但是我注意到React.addons.cloneWithProps适用于标准标记(例如<div>
),但不适用于作为组件的子代。
这是该问题的有效示例。 我希望两个div都具有红色背景,但是使用组件创建的div没有。
http://jsfiddle.net/ydpk2dp7/1/
var Main = React.createClass({
render: function() {
children = React.Children.map(this.props.children, function (c, index) {
return React.addons.cloneWithProps(c, {
style: {
background: 'red'
}
});
});
return (
<div>
{children}
</div>
);
},
});
var Comp = React.createClass({
render: function() {
return (
<div>{this.props.children}</div>
);
}
});
React.render(
<Main>
<div>1</div>
<Comp>2</Comp>
</Main>
, document.body);
我不确定这是否是错误,但我会将React组件包装在不属于父组件的父组件中。 下面提供了一个工作结果。
var Main = React.createClass({
render: function() {
children = React.Children.map(this.props.children, function (c, index) {
return React.addons.cloneWithProps(c, {style: {background: 'red'}});
});
return (
<div>
{children}
</div>
);
},
});
var Comp = React.createClass({
render: function() {
return (
<div>{this.props.children}</div>
);
}
});
React.render(
<Main>
<div>
<Comp>2</Comp>
<Comp>3</Comp>
<Comp>4</Comp>
</div>
</Main>
, document.body)
晚会晚了,但是我想以后遇到的人都会帮忙。
问题是您要放弃Comp
的style
道具:
var Comp = React.createClass({
render: function() {
var style = this.props.style; // you weren't passing this to the <div> below
return (
<div style={style}>{this.props.children}</div>
);
}
});
最好从props
提取您需要的东西,然后传递其余的东西。 使用ES2015的解构传播工具轻松完成:
var Comp = React.createClass({
render: function() {
var { children, ...props } = this.props;
return (
<div {...props}>{ children }</div>
);
}
});
这将允许在您最初编写时没有想到的组件上指定prop。
现在,例如,您现在可以添加一个onClick
处理程序,并期望它可以工作:
<Comp onClick={this.onClick} />
请记住 ,只有“ DOM”元素上的props
才具有特殊含义。 要自定义元素,它们只是您可以随意解释的常规属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.