【问题标题】:how to pass ref from parent to child Touchable Opacity in react native?如何在本机反应中将 ref 从父级传递给子级 Touchable Opacity?
【发布时间】:2021-01-09 06:23:15
【问题描述】:

我在父转换视图中有一个转换参考我想传递给一个孩子:

const transition = (
  <Transition.Together>
    <Transition.In type="fade" durationMs={300} />
    <Transition.Change />
    <Transition.Out type="fade" durationMs={300} />
  </Transition.Together>
);
const FiltersModal: FC = () => {
const transitionRef = useRef<TransitioningView>(null);
return (
<FiltersContainer ref={transitionRef} transition={transition}>
 ...
{primaryFilters.map((primaryFilter, i) => (
    <FilterOption key={i} ref={transitionRef} label={primaryFilter}>
      {primaryFilter}
    </FilterOption>
  ))}

这是我从这里得到答案后的过滤器选项:ForwardRef error with typescript and react-native:

const FilterOption: React.ComponentType<FilterOptionProps> = React.forwardRef(
  ({ label }: FilterOptionProps, ref?: React.Ref<TransitioningView>) => {
    const [isSelected, setiIsSelected] = useState(false);
    const onPress = () => {
      if (ref.current) ref.current.animateNextTransition();
      setiIsSelected((prevIsSelected) => !prevIsSelected);
    };
    if (isSelected) return null;
    return (
      <Button>
        <Typography
          {...{
            fontFamily: FONTS_MONTSERRAT_500,
            fontWeight: 500,
            fontSize: 14,
            fontStyle: "normal",
            lineHeight: 20,
            color: "#00B0F0",
          }}
        >
          {label}
        </Typography>
        <AntDesign name="plus" color="#00b0f0" size={10} />
      </Button>
    );
  }
);

但是我有这个警告并且不能参考 ref.current.:

Type 'ForwardRefExoticComponent<Pick<FilterOptionProps, "label"> & RefAttributes<TransitioningView>>' ....

如何在 react native + typescript 的 touchableOpacity 中使用 forwardref?

【问题讨论】:

  • 使用它作为专业名称发送参考 ,并在组件中使用 transitionRef.current?.animateNextTransition()

标签: reactjs typescript react-native


【解决方案1】:

这对我有用:

interface FilterOptionProps {
  label: string;
} 

const FilterOption: React.ForwardRefExoticComponent<
  FilterOptionProps & React.RefAttributes<TransitioningView>
> = React.forwardRef(({ label }, ref) => {
...

if((ref as React.RefObject<TransitioningView>).current)
(ref as React.RefObject<TransitioningView>).current.animateNextTransition()

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 2017-11-07
    • 2018-09-17
    相关资源
    最近更新 更多