【问题标题】:cannot destruct the style object无法破坏样式对象
【发布时间】:2017-07-21 18:54:12
【问题描述】:

我正在尝试解构样式对象,但它在const { errorTextStyle } = myStyle; 行上给了我错误,说:Unexpected token (8:8)"。 下面是整个代码:

import React, { Component } from 'react';
import { Platform, Dimensions, Text } from 'react-native';
import { Card, CardSection, Button, Input } from './common';

class LoginForm extends Component {
  /////////////////////
  state = {email: '', password: '', error: ''};
  const { errorTextStyle } = myStyle;
  /////////////////////    methods
  onButtonPress(){
    const { email, password } = this.state;
    firebase.auth().signInWithEmailAndPassword(email,password).
    catch(() => {
      firebase.auth().createUserWithEmailAndPassword(email,password).
      catch(() => {
        this.setState({error: 'Authentication Failed.'});
      });
    });
  }
  //////////////////////   render
  render(){
    return(
      <Card>

        <CardSection >
          <Input
            placeholder="Type here :)"
            onChangeText={ email => this.setState({ email }) }
            value={ this.state.email }
            label={ 'Email: ' }
            autoCorrect={false}
          />
        </CardSection >

        <CardSection >
          <Input
            placeholder="Type here :)"
            onChangeText={ password => this.setState({password}) }
            value={this.state.password}
            label={'Password: '}
            autoCorrect={false}
            secureTextEntry
          />
        </CardSection >
        <Text style={ errorTextStyle }>
          {this.state.error}
        </Text>
        <CardSection>
          <Button onPress={this.onButtonPress.bind(this)}>
            Login :)
          </Button>
        </CardSection>

      </Card>
    );
  }
}


const myStyle = {
  errorTextStyle: {
    fontSize: 20,
    alignSelf: 'center',
    color: 'red'
  }
};

export default LoginForm;

【问题讨论】:

  • 您在class 的上下文中输入,它不允许使用表达式。你想达到什么目的?你想要在constructor 里面吗?
  • 把那一行,带有const { .. } = style 的那一行放在你的类定义之上。当你在它的时候,把样式对象放在顶部
  • 但是当我有一个函数组件时,我把它放在函数内部,为什么它有效,但在这里我们应该把它放在课堂之外?请把它写成答案,谢谢
  • 顺便说一句,我确实在课堂上撅了撅嘴,现在它说:cannot read property errorTextStyle` od undifined`
  • 您将要在您希望使用该变量的方法中进行解构。在这种情况下,您将在 render() 方法中使用它,因此您应该在类的 render() 方法内的 return 语句上方对其进行解构。

标签: reactjs react-native ecmascript-6


【解决方案1】:

由于变量在render 中使用,因此将该代码移动到该方法中。您只能在class 声明中声明方法和fields,表达式必须在方法中。 state = ... 为您工作,因为这是一个字段声明。请尝试以下操作:

render(){
  const { errorTextStyle } = myStyle;
  ...
}

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2017-07-10
    • 2017-03-24
    相关资源
    最近更新 更多