繁体   English   中英

我可以在React组件上放置对象/变量吗? (得到ESLint错误no-undef)

[英]Can I place objects/variables on a React component? (getting ESLint error no-undef)

这在React Native中可以很好地工作,并且在React中也可以正常运行。 我假设是因为我使用的是Create React App,但这里却出现了ESLint错误,但不是React Native。 我不能禁用no-undef,因为这会影响很多有用的检查,也不确定我可以自定义eslint来匹配React Native的方式。

如果不允许,将变量/对象放在React组件上的最佳方法是什么? 一个示例用例是我要从样式对象引用this.props。

理想情况下,我想避免将内容放在render方法上,因为样式对象可能会变得很大(或者这是最好的方法吗?)

我想做的事的例子(可以,但是出现ESLint错误):

export class Test extends Component {
    style = {
        opacity: this.props.fade ? 0.5 : 1,

        color: "white",

        ...this.props.style
    }
    render() {
        return(
            <div style={this.style}>
                {this.props.children}
            </div>
        )
    }
}

在此处输入图片说明

谢谢!

喂!

您应该养成从组件中提取样式的习惯。 在我的项目中,我在组件旁边或子文件夹中有一个文件。

您可能还应该使用StyleSheet.create在一个地方定义几种样式。 链接到文档

话虽如此,我要么做这两个之一:

// Styles/Test.js
export default StyleSheet.create({
  test: {
    color: 'white'
  },
  otherStyle: {},
  evenOtherStyle: {}
});

// Test.js
import styles from './Styles/Test';

export class Test extends Component {
    render() {
        return(
            <div style={[
              styles.test,
              { opacity: this.props.fade ? 0.5 : 1 },
              ...this.props.style
            ]}>
                {this.props.children}
            </div>
        )
    }
}

或者,如果您不喜欢组件中的动态样式,请添加样式方法,或者在构造函数中执行:

样式:

// Test.js
import styles from './Styles/Test';

export class Test extends Component {
    addStyles() {
      const opacityStyle = { opacity: this.props.fade ? 0.5 : 1 };
      return [styles.test, opacityStyle, ...this.props.style];
    }

    render() {
        return(
            <div style={this.addStyles()}>
                {this.props.children}
            </div>
        )
    }
}

构造函数中的样式:

// Test.js
import styles from './Styles/Test';

export class Test extends Component {
    constructor(props) {
      super(props);

      this.testStyles = [
        styles.test,
        { opacity: props.fade ? 0.5 : 1 },
        ...props.style
      ];
    }

    render() {
        return(
            <div style={this.testStyles}>
                {this.props.children}
            </div>
        )
    }
}

希望这可以帮助

我遇到了同样的错误,只需检查Eslint和关系插件,然后确保它们彼此兼容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM