简体   繁体   English

React-Bootstrap中的Form.Control类型密码始终呈现一个我无法删除的默认密码

[英]Form.Control type password in React-Bootstrap always renders an default password that i can't remove

I am doing the login page and i realized i cannot set the default values of the Form.Control type password input!!! 我正在登录页面,我意识到我无法设置Form.Control类型密码输入的默认值!

class Login extends Component {

  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: 'thisIsMyDefaultPassword',
      isLoading: false,
      redirectToReferrer: false
    };
  }


  handleChange = name => event => {
    let update = {};
    update[`${name}`] = event.target.value;
    this.setState(update);
  }

  handleFocus = () => {
    this.setState({ password: '' });
  }

  handleSubmit = () => event => {
    let data = {
      email: this.state.email,
      password: this.state.password
    }
    this.props.login(data)
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('componentDidUpdate');
    let { currentUser } = this.props;
    console.log('currentUser ', currentUser, 'prevProps.currentUser ', prevProps.currentUser );
    if (JSON.stringify(prevProps.currentUser) !== JSON.stringify(currentUser)) {
      console.log('currentUser !=');
      if (currentUser._id) {
        this.setState({
          redirectToReferrer: true
        })
      }
    }
  }

  render() {
    let { email, password , isLoading, redirectToReferrer } = this.state;
console.log('password when rendered', password);
    if (redirectToReferrer) {
        return <Redirect to={'/'} />;
    }

    return (
      <div className="loginWrapper">
        <div className="loginContainer">
          <Form>
            <Form.Group controlId="formGroupEmail">
              <Form.Label>Email Address</Form.Label>
              <Form.Control
                type="email"
                value={email}
                onChange={this.handleChange('email')}
                placeholder="Enter Email"
              />
            </Form.Group>
            <Form.Group controlId="formGroupPassword">
              <Form.Label>Password</Form.Label>
              <Form.Control
                type="password"
                defaultValue={this.state.password}
                onFocus={this.handleFocus}
                onChange={this.handleChange('password')}
                placeholder="Password"
              />
            </Form.Group>
          </Form>
          <Button
            variant="primary"
            size="lg"
            disabled={isLoading}
            onClick={this.handleSubmit()}
            block
          >
            {isLoading ? 'Loading…' : 'LOGIN'}
          </Button>
        </div>
      </div>
    );
  }
}

i expect the default values rendered to be controlled by the default state of my component. 我希望呈现的默认值由组件的默认状态控制。 But it just don't work. 但这根本不起作用。 I have tried defaultValue / value / and defaultValue with value. 我尝试了defaultValue / value /和带有value的defaultValue。 but there is still this default number being rendered in the password input .. The above are my latest codes i am still facing the problem although i crack it with onFocus. 但是仍然在密码输入中呈现了此默认数字。.上面是我的最新代码,尽管我使用onFocus破解了该代码,但仍然遇到了问题。 If there's any better improvement to my codes please comment below too. 如果我的代码有更好的改进,请在下面也发表评论。 An Advance thank you to all commenters. 预先感谢所有评论者。 really appreciate the help of this community. 非常感谢这个社区的帮助。

Below are the console logs for console.log('password when rendered', password) IT shows that react-bootstrap javascript is clearning the password and setting as 0346: 以下是console.log('渲染时输入的密码',密码)的控制台日志。它显示react-bootstrap javascript正在清除密码并将其设置为0346:

password when rendered thisIsMyDefaultPassword
Login.js:51 password when rendered 
Login.js:51 password when rendered 0346

Thus concluding that the defaultValue for the type password does not work ? 因此得出结论,类型密码的defaultValue不起作用?

There are two type of valued components(TextField, Checkbox, etc.): 有价值的组件有两种类型(TextField,Checkbox等):

  1. Controlled - The component whose value is controlled by the code implementation. 受控 -其值由代码实现控制的组件。 In this type of component you have to set value prop of the component with the value source and handle it's onChange to get the value and update in the future source. 在这种类型的组件中,您必须使用值源设置组件的value prop并处理它的onChange以获取值并在将来的源中进行更新。

    <TextField value={this.state.password} onChange={(event) => this.setState({ password: event.target.value })} />

  2. Un-controlled - The component which has a default value and that value can changed without any trigger/handling in the component code. 不受控制 -具有默认值的组件,该值可以更改而无需组件代码中的任何触发器/处理。 These components have a prop 'defaultValue' populated with the initial value you want to assign. 这些组件都有一个属性“ defaultValue”,其中填充有您要分配的初始值。

    <TextField defaultValue={this.state.password} />

You can't use both value and defaultValue on same component. 您不能在同一组件上同时使用valuedefaultValue

In your case You have to remove defaultValue prop, as you need a controlled component to make its value persist. 在您的情况下,您必须删除defaultValue ,因为您需要一个受控组件来使其值持久化。

The value props is too much here, if you get rid of it, you can change the input. 这里的props值太多,如果您放弃它,可以更改输入。 Additionally, you always provide the string "password" to your onChange handler as a value. 此外,您始终将字符串“ password”作为值提供给onChange处理程序。 This might not be what you want to do, but instead using the actual password the user is entering. 这可能不是您要执行的操作,而是使用用户输入的实际密码。

In your render method: 在您的渲染方法中:

<p>Current password: {this.state.password}</p>
<Form>
  <Form.Group controlId="formGroupPassword">
    <Form.Label>Password</Form.Label>
    <Form.Control
      type="password"
      defaultValue={this.state.password}
      onChange={this.handleChange('password')}
      placeholder="Password"
    />
  </Form.Group>
</Form>

And your handleChange function could look like: 您的handleChange函数可能类似于:

handleChange = name => event => {
  this.setState({ password: event.target.value });
};

Example: https://codesandbox.io/s/8x8zw28nv2 示例: https//codesandbox.io/s/8x8zw28nv2

You have the same value for defaultValue and value , seems like it doesn't make sense because if value has a value, that value will be rendered. 您对defaultValuevalue具有相同的值,似乎没有意义,因为如果value具有值,则将呈现该值。 Try matching defaultValue to another value or just remove defaultValue . 尝试将defaultValue与另一个值匹配,或者只是删除defaultValue Does your onChange work? 您的onChange是否有效? Seems like not. 好像没有。 Are you implemented your handleChange ? 您实现了handleChange吗? Because you are using controlled inputs. 因为您使用的是受控输入。 Try this: 尝试这个:

  handleChange = e => {
    this.setState({
        password: e.target.value
    })
  }

  <Form>
    <Form.Group controlId="formGroupPassword">
      <Form.Label>Password</Form.Label>
      <Form.Control
            type="password"
            value={password}
            onChange={this.handleChange}
            placeholder="Password"
       />
    </Form.Group>
  </Form>

暂无
暂无

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

相关问题 改变 React-Bootstrap Form.Control 元素的颜色 - Changing color of React-Bootstrap Form.Control elements 如何删除React-Bootstrap中默认提供的FormControl组件的class =“ form-control” - How can I remove the class=“form-control” that comes by default the FormControl component in React-Bootstrap React Bootstrap Form.Control 未采用默认值 - React Bootstrap Form.Control default value not taken 在使用 react-bootstrap 做出反应时,无法减小带有浮动标签的输入字段(form.control)的大小 - Unable to reduce the size of the input field (form.control) with floating label in react in using react-bootstrap react-bootstrap - Form.Control defaultValue 重新渲染时未更新 - react-bootstrap - Form.Control defaultValue not updated when re-rendered 我可以以编程方式更新 React bootstrap 的值吗<form.control>更新后?</form.control> - Can I programmatically update the values of React bootstrap <Form.Control> after it's been updated? React bootstrap Form.Control onClick 回调不起作用? - React bootstrap Form.Control onClick callback is not working? 在反应引导程序 Form.Control 中显示可编辑值 - Display editable value in react bootstrap Form.Control 如何获取 Form.Control 的价值 - React Bootstrap Date Picker? - How to get value of Form.Control - React Bootstrap Date Picker? 如何从 React Bootstrap 中的 Form.Control 获取值? - How do I get the value from Form.Control in React Bootstrap?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM