javascript-通过React.cloneElement维护组件引用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-通过React.cloneElement维护组件引用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2376字,纯文字阅读大概需要4分钟。
内容图文
我一直在测试使用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);
}
}
)
);
内容总结
以上是互联网集市为您收集整理的javascript-通过React.cloneElement维护组件引用全部内容,希望文章能够帮你解决javascript-通过React.cloneElement维护组件引用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。