我一直在测试使用React.cloneElement()扩展组件子级的可能限制/危险.我发现的一种可能的危险是可能会覆盖ref和key之类的道具.
但是,根据React的0.13 release candidate(早在2015年):
However, unlike JSX and cloneWithProps, it also preserves refs. This means that if you get a child with a ref on it, you won’t accidentally steal it from your ancestor. You will get the same ref attached to your new element.
[…]
Note:
React.cloneElement(child, { ref: 'newRef' })
DOES override the ref so it is still not possible for two parents to have a ref to the same child, unless you use callback-refs.
我写了一个small React application,它克隆了通过的子组件,并在两个级别上测试了引用的有效性:
class ChildComponent extends React.Component{
constructor(props){
super(props);
this.onClick = this.onClick.bind(this);
this.extendsChildren = this.extendChildren(this);
}
onClick(e) {
e.preventDefault();
try{
alert(this._input.value);
}catch(e){
alert('ref broken :(');
}
}
extendChildren(){
return React.Children.map(this.props.children, child => {
return React.cloneElement(
child,
{
ref: ref => this._input = ref
}
);
});
}
render() {
return(
<div>
<button onClick={this.onClick}>
ChildComponent ref check
</button>
{this.extendChildren()}
</div>
);
}
}
class AncestorComponent extends React.Component{
constructor(props){
super(props);
this.onClick = this.onClick.bind(this);
}
onClick(e) {
e.preventDefault();
try{
alert(this._input.value);
}catch(e){
alert('ref broken :(');
}
}
render() {
return (
<div>
<p>
The expected behaviour is that I should be able to click on both Application and ChildComponent check buttons and have a reference to the input (poping an alert with the input's value).
</p>
<button onClick={this.onClick}>
Ancestor ref check
</button>
<ChildComponent>
<input ref={ref => this._input = ref} defaultValue="Hello World"/>
</ChildComponent>
</div>
);
}
}
但是,ChildComponent内部的cloningElements会覆盖输入字段中的AncestorComponent的ref属性,我希望在该位置保留该ref属性,以及我定义为React.cloneElement一部分的新ref.
您可以通过运行CodePen进行测试.
我做错什么了吗,或者此功能此后被删除了?
解决方法:
根据丹·阿布拉莫夫(Dan Abramov)的response,即使使用回调,覆盖引用仍将覆盖引用.您需要在回调声明中调用当前引用:
return React.Children.map(this.props.children, child =>
React.cloneElement(child, {
ref(node) {
// Keep your own reference
this._input = node;
// Call the original ref, if any
const {ref} = child;
if (typeof ref === 'function') {
ref(node);
}
}
)
);