如果我有
<Parent>
<Child1 />
<Child2 />
<Child3 />
</Parent>
我想从Child2
到refs="child2refs"
,我该怎么做?
如果我有
<Parent>
<Child1 />
<Child2 />
<Child3 />
</Parent>
我想从Child2
到refs="child2refs"
,我该怎么做?
如果无法避免,则从React docs中提取的建议模式为:
import React, { Component } from 'react';
const Child = ({ setRef }) => <input type="text" ref={setRef} />;
class Parent extends Component {
constructor(props) {
super(props);
this.setRef = this.setRef.bind(this);
}
componentDidMount() {
// Calling a function on the Child DOM element
this.childRef.focus();
}
setRef(input) {
this.childRef = input;
}
render() {
return <Child setRef={this.setRef} />
}
}
Parent将函数作为props 转发到Parent's this
.当React调用Child's ref
prop setRef
时,它会将Child's ref
分配给Parent's childRef
属性.
Ref-forwarding是一种 Select 性加入功能,允许一些组件获取他们接收到的Ref,并将其进一步向下传递(换句话说,"转发"给子组件).
我们创建了Components个,将其ref
个和React.forwardRef
个向前推进.
import React from "react";
const LibraryButton = React.forwardRef((props, ref) => (
<button ref={ref} {...props}>
FancyButton
</button>
));
class AutoFocus extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
this.onClick = this.onClick.bind(this);
}
componentDidMount() {
this.childRef.current.focus();
}
onClick() {
console.log("fancy!");
}
render() {
return <LibraryButton onClick={this.onClick} ref={this.childRef} />;
}
}
创建的Components正在将其ref
转发到子 node .
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
const {forwardedRef, ...rest} = this.props;
// Assign the custom prop "forwardedRef" as a ref
return <Component ref={forwardedRef} {...rest} />;
}
}
// Note the second param "ref" provided by React.forwardRef.
// We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
// And it can then be attached to the Component.
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}
见React docs中的Forwarding Refs.