【问题标题】:onChange react nativeonChange 反应原生
【发布时间】:2021-05-03 19:55:50
【问题描述】:

我有一个问题,当我将用户 : 1 和密码 123 显示在控制台空字符串中时,我不明白为什么有人可以帮助我?

export default class App extends React.Component {

  // Setting up Login Activity title.
  constructor(props) {
    super(props)
    this.state = { UserName: '',Userpassword: ''}

    this.login = this.login.bind(this);
    this.onChange = this.onChange.bind(this)

  }


onChange(e) {
  this.setState({ [e.target.name]: e.target.value });
  console.log(this.state);
}



<TextInput

          placeholder="Enter User Name"  
       
          onChange={this.onChange}

          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}

        />

 <TextInput

     
          placeholder="Enter Password"

         
           onChange={this.onChange}
       
          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}
          secureTextEntry={true}

        />

我添加了我的代码控制台输出的朋友,用户:1,密码:123´

我的出局

【问题讨论】:

    标签: javascript reactjs react-native jsx


    【解决方案1】:

    问题

    1. onChange 事件没有要从event.target 解构的name 属性。 name 未定义并解析为第三个键 ""
    2. React 状态更新是异步的,因此您无法在将更新排入队列的同一渲染周期中通过控制台记录更新的状态。请注意,您的所有控制台日志都是 onChange 事件后面的“周期”。

    解决方案

    将您的 onChange 回调重构为一个柯里化函数。附加到 onChangeText 属性,以便传递文本值,并为 TextInput 提供与其正在更新的状态匹配的“名称”值。

    onChange = name => value => {
      this.setState({ [name]: value });
    }
    
    ...
    
    <TextInput
      placeholder="Enter User Name"  
      onChangeText={this.onChange('UserName')}
      underlineColorAndroid='transparent'
      style={styles.TextInputStyleClass}
    />
    

    要记录更新的状态,请使用 componentDidUpdate 生命周期方法。

    componentDidUpdate() {
      console.log(this.state);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 2021-11-07
      • 2018-03-30
      • 2017-11-09
      • 2018-12-07
      相关资源
      最近更新 更多