我正在尝试将useRef
详细信息从父组件传递到子组件。
如果child是一个基本组件,则它的工作方式如下。
const Apple = React.forwardRef(({
}, ref) => {
console.log(`Apple ref: ${ref}`); // can print value, ref not null
return (
<div ref={ref}>
{`ref is: ${ref && ref.current}`}
</div>
);
});
export default Apple;
但是如果我使用redux和compose来 Package 组件,如下所示,ref最终会为null。
我该怎么补救呢?
import { compose } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
const Apple = React.forwardRef(({
p1,
p2,
p3,
}, ref) => {
console.log(`Apple ref: ${ref}`); // no longer working, ref prints null.
return (
<div ref={ref}>
{`ref is: ${ref && ref.current}`}
</div>
);
});
const mapStateToProps = someFunction({
state: getState,
});
const mapDispatchToProps = {
a: a1,
b: a2,
c: a3,
};
const chainUp = compose(
withRouter,
connect(mapStateToProps, mapDispatchToProps)
);
export default chainUp(Apple);
1条答案
按热度按时间a9wyjsp71#
一般来说,在现代React应用程序中,您可能不应该使用
withRouter
或connect
。这些HOC对于向后兼容遗留类组件是必需的,但是在函数组件中,您可以(并且应该!)只使用useRouter
、useSelector
和useDispatch
。