代码之家  ›  专栏  ›  技术社区  ›  user5932019

react native:访问父组件内部的子组件函数

  •  0
  • user5932019  · 技术社区  · 6 年前

    目标:创建一个可重用的OptionFan组件,该组件允许子组件作为ChildButton组件。 问题:无法访问OptionFan(父)组件方法“ShowOptions()”内ChildButton的方法“Flyout()”

    在选项风扇组件中:

     showOptions = () => {
            let animations = this.props.children.map((child, i) => {
                this.refs.child.flyOut();
            });
            Animated.stagger(this.props.staggerDelay, animations).start();
        }
        renderOptions = () => {
           return this.props.children.map((child, i) => {
               return <ChildButton ref={child} siblings={this.props.children.length} key={i} icon={} number={i} size={} />
    
           })
        }
    

    在ChildButton组件中:

    componentDidMount() {
            this.props.ref(this);
        }
    
    flyOut = () => {
            const {number, size} = this.state;
            let offset = this.findChildCoordinates(number);
            Animated.timing(
                this.state.move,
                {toValue: offset}
            ).start();
        }
    

    所需方法在代码建议中不可访问, 我的方法有什么不正确?

    1 回复  |  直到 6 年前
        1
  •  1
  •   aravind_reddy    6 年前

    你需要把它们绑在你的班上。改变你的 optionFan 组件如下:

    Option Fan:

    showOptions = () => {
        let animations = this.props.children.map((child, i) => {
            this.child.flyOut();
        });
        Animated.stagger(this.props.staggerDelay, animations).start();
    }
    renderOptions = () => {
       return this.props.children.map(i => {
           return <ChildButton ref={ Ref =>(this.child = Ref)} siblings={this.props.children.length} key={i} icon={} number={i} size={} />
    
       })
    }
    

    有关更多参考,请参阅 https://github.com/kriasoft/react-starter-kit/issues/909#issuecomment-252969542