【问题标题】:ReactJS createRef for N components, all point to the final one in the listReactJS createRef for N 个组件,都指向列表中的最后一个
【发布时间】:2018-11-15 07:29:50
【问题描述】:

我有 3 个组件,App、Parent 和 Child。 App 使用 Parent 提供的方法,将孩子注册到 Parent。这是为了让 Parent 收集它所包含的 Children 的 Refs(创建依赖关系图)。

Child 有一个名为 Animate 的方法,Parent 通过创建的 refs 调用该方法。

当我尝试打印 dependencyMap 时,我可以看到正在生成一个数组,这是我所期望的。

但是当我尝试使用 dependencyMap 从 Parent 访问子组件时,它总是调用子列表中的最后一个。

也就是说,当我尝试在 Parent.js 中使用 animateDependentChildren 为 设置动画时,即使我为 CustomComponent1 传递了正确的 ID,CustomComponent2 也只会获得动画。

App.js
export default class App extends React.Component {
  render(){
    return(
      <Parent>
        {
          (props)=>{
            return(
              <View>
                <CustomComponent1 ref={props.register('s1')} key={1}>Text</CustomComponent1>
                <CustomComponent2 ref={props.register('s2')} key={2}>Text2</CustomComponent2>
                <ListComponent id={'s1'} key={3}/>
                <ListComponent id={'s2'} key={3}/>
              </View>
            )
          }
        }
      </Parent>
    );
  }
}


Parent.js
class Parent extends React.Component{
  constructor(props) {
    super(props);
    this.dependencyMap = {}
  }

  render() {
    return (
      <View>
        {this.props.children({
         register: this.register.bind(this)
        })}
      </View>
    );
  }

  register(dependentOn){
    let dependentRef = React.createRef();

    if(!this.dependencyMap[dependentOn]){
      this.dependencyMap[dependentOn] = [];
    }
    this.dependencyMap[dependentOn].push(dependentRef);

    return dependentRef;
  }

  animateDependentChildren(listId){
    let subscribers = this.dependencyMap[listId];

    subscribers.forEach(subscriber => {
        console.log('subscriber', subscriber);
        console.log('subscriber dom', subscriber.current);
        this.refs[subscriber].animate(scrollObj); // <-This function always animates the last of the list of children (ie CustomComponent2)
    });
  }
}

知道我在这里做错了什么吗? React.createRef 不能用来创建多个引用,然后单独调用它们吗?

【问题讨论】:

  • 多次引用不存在这样的问题。他们是独立的。考虑向stackoverflow.com/help/mcve 提供演示。问题可能出在其他地方。

标签: reactjs react-native react-ref


【解决方案1】:

由于 subscriber 是组件引用,请尝试更改此行:

this.refs[subscriber].animate(scrollObj);

...到:

subscriber.animate(scrollObj);

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多