首页 > 解决方案 > 将 onPress 处理程序附加到在组件外部构造的 Text

问题描述

我有我的组件类,我们称之为MyComponent。它有一个复杂的执行逻辑,但这是省略了不必要的代码片段后的样子:

class MyComponent extends Component {

    justWarn(input) {
        console.warn(input);
        // do something with `this` as well
    }

    render() {
        return (
            <View>
                {this.props.myText}
            </View>
        );
    }
}

const mapStateToProps = () => {
    // Call the getText function here
    return {
        myText: getText()
    };
}

export default connect(mapStateToProps)(MyComponent);

现在该函数getText在其他文件中定义,如下所示:

function getText() {
    // Let's assume it returns hard-coded value for the sake of brevity

    return (
        <Text>
            <Text>I am the first part</Text>
            <Text
            onPress={function(){
                // I want to call the function that is defined inside MyComponent
                // since this Text will eventually be a part of MyComponent
                this.justWarn('Warn me in the yellow box')
            }}
            >I am the clickable part
            </Text>
        </Text>
    );
}

当我尝试调用上面justWarn定义的MyComponentfrom 中Text定义的方法时,我得到一个错误undefined is not a function, evaluating this.justWarn

我的问题是,我没有使用箭头函数,因此this在我声明处理程序时不受约束onPress。它实际上是在什么时候Text被调用的MyComponent,所以不应该this对应MyComponent并且上面的代码应该可以正常工作吗?

我在这里做错了什么?有没有办法通过将getTextMyComponent拆分为两个文件来实现这一点?

谢谢。

标签: reactjsreact-native

解决方案


问题是getText没有this上下文,因此您需要以某种方式绑定它以获取上下文。

实现这一目标的一种方法是MyComponent像这样进行更改-

class MyComponent extends Component {

    justWarn(input) {
        console.warn(input);
        alert(input)
        // do something with `this` as well
    }

    render() {
        const myText = this.props.myText.bind(this)
        return (
            <View>
                <Text>something should render</Text>
                {myText()}
            </View>
        );
    }
}

const mapStateToProps = () => {
    // Call the getText function here
    return {
        myText: getText
    };
}

export default connect(mapStateToProps)(MyComponent);

...

然后像这样在 onPress 事件处理程序中使用箭头函数 -

function getText() {
    // Let's assume it returns hard-coded value for the sake of brevity

    return (
        <Text>
            <Text>I am the first part</Text>
            <Text
              onPress={() => {this.justWarn('Warn me in the yellow box')}}
            >I am the clickable part
            </Text>
        </Text>
    );
}

...

希望能帮助到你。


推荐阅读