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

React Native-从作为prop传递的函数调用方法

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

    我在一个叫做 react-native-linkedin

    现在我需要调用一个在LinkedInModal类中打开的方法,这个类与接收renderButton作为prop的类相同。

    如何从renderButton方法调用此“open”方法?我已尝试:

    LinkedInModal.open()
    

    renderButton = () => {
            return (React.createElement(TouchableOpacity, 
                      { accessibilityComponentType: 'button', accessibilityTraits: ['button'], 
                        onPress: LinkedInModal.open() 
                      },
                    React.createElement(Text, {style: {color: "#FFF"}}, "Continue with Linkedin")));
        }
    

    并将其传递给组件,如下所示:

    <LinkedInModal
                            clientID="..."
                            clientSecret="..."
                            redirectUri="https://www.linkedin.com/developer/apps"
                            onSuccess={token => this.linkedinLogin(token.access_token)}
                            linkText="Continue with Linkedin"
                            renderButton={this.renderButton}
                        />
    

    我得到的错误是:

        TypeError: _reactNativeLinkedin.default.open is not a function. 
    (In '_reactNativeLinkedin.default.open()', '_reactNativeLinkedin.default.open' is undefined)
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Eduardo    6 年前

    解决方案是创建一个引用:

    linkedRef = React.createRef();
    

    然后在调用组件时,将其作为道具传递:

                <LinkedInModal
                    ref={this.linkedRef}
                    clientID="..."
                    clientSecret="..."
                    redirectUri="https://www.linkedin.com/developer/apps"
                    onSuccess={token => this.linkedinLogin(token.access_token)}
                    linkText="Continue with Linkedin"
                    renderButton={this.renderButton}
                />
    

    在我的自定义方法中使用它:

    onPress={() => this.linkedRef.current.open()}>
    
        2
  •  0
  •   Custodio    6 年前

    看来你不是在包装这件衣服 Text 你能试试吗

    renderButton = () => (
      <TouchableOpacity 
          accessibilityComponentType="button" 
          accessibilityTraits={['button']}
          onPress={() => LinkedInModal.open()}>
        <Text style={{color: "#FFF"}}> Continue with Linkedin </Text>
      </TouchableOpacity>
    )
    
    
    推荐文章