forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
import React from "react";
// 通过React.forwardRef,可以将ref从父组件传下去,否则ref的prop是会被React.createElement处理掉的
const Child = React.forwardRef((props, ref) => {
return <div ref={ref}>{props.initText}</div>;
});
class Parent extends React.Component {
constructor(props) {
super(props);
this.fnRef = null;
this.createdRef = React.createRef(); // { current: null }
this.childDiv = React.createRef();
}
componentDidMount() {
setTimeout(() => {
// string ref, 会在this.refs的对应key上挂载ref实例(dom或者class component)
// 过时的,不推荐使用
this.refs.div1.innerHTML = "string ref";
// 回调ref,直接挂到实例属性上了
this.fnRef.innerHTML = "function ref";
// createRef的方式,会挂载到.current上,推荐
this.createdRef.current.innerHTML = "created ref";
this.childDiv.current.innerHTML = 'forward ref';
}, 1000);
}
render() {
return (
<div>
{/* ref的三种使用方式 */}
<div ref="div1">test</div>
<div
ref={ref => {
this.fnRef = ref;
}}
>
test
</div>
<div ref={this.createdRef}>test</div>
<Child initText="child" ref={this.childDiv} />
</div>
);
}
}
export default Parent;
Metadata
Metadata
Assignees
Labels
No labels