REACT - 如何在课堂外使本地变量可访问

时间:2017-02-02 01:49:39

标签: reactjs redux redux-form

我遇到了让我的本地变量可以在课堂外访问的问题

class LoginForm extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {

    const {
      handleSubmit,
      pristine,
      reset,
      submitting,
      submitData,
      renderTextField,
      validation
    } = this.props;

    return (
      <Card className="container">
        <form onSubmit={handleSubmit(submitData)}>
          <h2 className="card-heading">Login</h2>

          <div className="field-line">
            <Field name="email" component={renderTextField} label="Email"/>
          </div>
        </form>
      </Card>
    )
  }
};
LoginForm = reduxForm({form: 'LoginForm', validation})(LoginForm);

export default LoginForm

我想在

中进行验证
  

LoginForm = reduxForm({form:&#39; LoginForm&#39;,validation})(LoginForm);

2 个答案:

答案 0 :(得分:0)

通常不鼓励用于此类目的的全局变量。其他答案中的原因非常详细,例如this answer

  

在javascript中不鼓励全局变量的主要原因是因为,在javascript中所有代码共享一个全局命名空间,javascript也隐含了全局变量,即。未在本地范围内显式声明的变量会自动添加到全局命名空间。过分依赖全局变量可能会导致同一页面上各种脚本之间发生冲突。

不是将验证(函数?)作为prop传递,而是考虑将其重构为帮助文件,然后将其导入到表单中。

示例:

//helpers.js

const validation = (someParams) => {
  return (
    // do validation here as required
  );
}

export default validation;

// LoginForm.js

import { validation } from './path/to/helpers';

...

LoginForm = reduxForm({form: 'LoginForm', validation})(LoginForm);
...

答案 1 :(得分:-1)

要创建一个全局类变量(不建议),请执行以下操作:

let my_global = 0;

class LoginForm extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {

    const {
      handleSubmit,
      pristine,
      reset,
      submitting,
      submitData,
      renderTextField,
      validation
    } = this.props;
    console.log(my_global); #we can access the global variable anywhere in here
    return (
      <Card className="container">
        <form onSubmit={handleSubmit(submitData)}>
          <h2 className="card-heading">Login</h2>

          <div className="field-line">
            <Field name="email" component={renderTextField} label="Email"/>
          </div>
        </form>
      </Card>
    )
  }
};
LoginForm = reduxForm({form: 'LoginForm', validation})(LoginForm);

export default LoginForm