【发布时间】:2020-03-27 06:18:33
【问题描述】:
我有两个组件。父母和孩子。
在父组件内部我有一个按钮。如果用户单击该按钮,我想对子组件内的另一个按钮执行 ScrollIntoView。
我想我想定义一个对子按钮 a 的引用,以便我在父按钮 onClick 内可以执行以下操作:
ref.scrollIntoView({block: 'end', behavior: 'smooth'});
这将滚动到子组件中的按钮。
这是一个缩小的例子:
ParentComponent.jsx
import React, {useRef} from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = props => {
const childReference = useRef(null);
const onClick = () => {
childReference.scrollIntoView({block: 'end', behavior: 'smooth'});
}
return (
<>
<...some other components>
<Button onClick={onClick}>Click me to be forwarded</Button>
<ChildComponent ref={childReference}/>
</>
);
};
ChildComponent.jsx
import React from 'react';
const ChildComponent = (props, ref) => {
const { name, value, description } = props;
return (
<...some other components>
<Button ref={ref}>You should be forwarded to me</Button>
);
};
ChildComponent.propTypes = {
name: PropTypes.string.isRequired,
value: PropTypes.number,
description: PropTypes.string,
};
ChildComponent.defaultProps = {
value: 0,
description: '',
};
export default React.forwardRef(ChildComponent);
我知道上面的代码不起作用,只是为了说明我想要实现的目标。
我真的尝试了通过谷歌搜索找到的所有其他解决方案,它们看起来都很简单,但它们似乎都不适用于我的用例。我也尝试过使用 forwardRef,但这也不能解决我的问题。
更新
我想我对什么不起作用有点含糊。我在执行过程中收到了很多不同的错误消息。
以下是其中之一:
函数组件不能被赋予 refs。尝试访问此 ref 将失败。你的意思是使用 React.forwardRef() 吗?
解决方案
好的。我想我会用@Vencovsky 提供的解决方案在这里组装这些部分。
这是问题中的两个示例组件的完整实现:
ParentComponent.jsx
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = props => {
const childReference = useRef(null);
const scrollIntoView = () => {
childReference.current.scrollIntoView({block: 'center', inline: 'center', behavior: 'smooth'});
}
return (
<>
<...some other component>
<Button onClick={scrollIntoView}>Click me to be forwarded</Button>
<ChildComponent ref={childReference}
</>
);
};
export default ParentComponent;
ChildComponent.jsx
import React, {forwardRef} from 'react';
import PropTypes from 'prop-types';
const ChildComponent = forwardRef((props, ref) => {
const { name, value, description } = props;
return(
<>
<...some other components>
<Button ref={ref}>You should be forwarded to me</Button>
</>
);
});
ChildComponent.propTypes = {
name: PropTypes.string.isRequired,
value: PropTypes.number,
description: PropTypes.string,
};
ChildComponent.defaultProps = {
value: 0,
description: '',
};
export default ChildComponent;
【问题讨论】:
-
看来你的按钮也是自定义组件。您确定将 ref 传递给那里的 html 按钮元素吗?
-
@JeroenWienk。这实际上是一个很好的建议。我想我应该先尝试一个基本的 HTML5 按钮,如果可行,我当然也应该更新我的自定义
Button。
标签: reactjs react-hooks js-scrollintoview react-ref