为什么this.state在native native中是未定义的?

Nik*_*aev 18 javascript reactjs react-native

我是反应原生,react.js和javascript的完整新手.我是Android开发人员,所以想试试RN.

基本上,区别在于onPress;

此代码显示'undefined'toggle()运行时:

class LoaderBtn extends Component {
    constructor(props) {
        super(props);
        this.state = { loading: false };
    }

    toggle() {
        console.log(this.state);
        // let state = this.state.loading;
        console.log("Clicked!")
        // this.setState({ loading: !state })
    }

    render() {
        return (
            <Button style={{ backgroundColor: '#468938' }} onPress={this.toggle}>
                <Text>{this.props.text}</Text>
            </Button>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码有效:

class LoaderBtn extends Component {
    constructor(props) {
        super(props);
        this.state = { loading: false };
    }

    toggle() {
        console.log(this.state);
        // let state = this.state.loading;
        console.log("Clicked!")
        // this.setState({ loading: !state })
    }

    render() {
        return (
            <Button style={{ backgroundColor: '#468938' }} onPress={() => {this.toggle()}}>
                <Text>{this.props.text}</Text>
            </Button>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

你能解释一下这个区别吗?

在Java/Kotlin中,我们有方法引用,基本上它传递函数,如果签名是相同的,比如onPress = () => {}toggle = () => {}

但在JS它不起作用:(

Dav*_*ton 29

在第一个示例toggle()中没有绑定到正确的问题this.

你可以在ctor中绑定它:

constructor(props) {
    super(props);
    this.toggle = this.toggle.bind(this);
    ...
Run Code Online (Sandbox Code Playgroud)

或者使用实例函数(在某些情况下可以):

toggle = () => {
    ...
}
Run Code Online (Sandbox Code Playgroud)

这种方法需要通过stage-2或更改构建transform-class-properties.

实例属性函数的警告是每个组件创建一个函数.如果页面上没有很多,这是可以的,但要记住这一点.一些模拟库也没有特别好地处理箭头函数(即箭头函数不在原型上,而是在实例上).

这是基本的JS; 这篇关于React Binding Patterns的文章可能有所帮助.


lar*_*arz 5

我认为正在发生的事情是范围问题.当您使用时,onPress={this.toggle}这不是您在切换功能中所期望的.但是,箭头函数表现出不同的行为并自动绑定到this.你也可以使用onPress={this.toggle.bind(this)}.

进一步阅读 -

ES6箭头功能

.bind()


小智 5

在第一个示例中发生的事情是您失去了“ this”的范围。通常,我要做的是在构造函数中定义所有函数,如下所示:

constructor(props) {
    super(props);
    this.state = { loading: false };
    this.toggle = this.toggle.bind(this);
}
Run Code Online (Sandbox Code Playgroud)

在第二个示例中,您使用的是ES6语法,该语法将自动绑定它(这就是为什么它起作用)。

然后在onPress函数内部,您需要调用所构建的函数。所以看起来像这样,

onPress={this.toggle}
Run Code Online (Sandbox Code Playgroud)