0

为什么受控输入更改时 PureComponent 不呈现

更改为 Component 解决了它

import React, { PureComponent } from 'react';

class Contact extends PureComponent {
state = {firstName:''}

 handleInput = ({ target }, name) => {
 const state = this.state;
 state[name] = target.value;
 this.setState(state);
};

render(){
 return (
    <input onChange={e => {
             this.handleInput(e, 'firstName');
           }} 
           value={this.state.firsName} />
  )
 }
}

它应该在打字时呈现新状态,但它没有

4

2 回答 2

2

尝试这样做:

import React, { PureComponent } from 'react';

class Contact extends PureComponent {
  state = {firstName:''}
  handleInput = name => ({target}) => this.setState({[name]: target.value})


  render() {
    return (
      <input
        onChange={this.handleInput('firstName')} 
        value={this.state.firsName} />
    )
  }
}

您遇到的主要问题是您直接改变了状态对象,您所做的就像这样做:this.state.someProp = 'foo'; this.setState(this.state);,这很糟糕。你永远不应该直接改变state.

我正在做的另一件事是我已经将该handleInput方法转换为高阶函数......这不是必需的,但 IMO 使代码更简洁。基本上这意味着this.handleInput('whatever')将返回一个函数,该函数接受“事件”作为其第一个(也是唯一的)参数并更新whatever状态的属性。

于 2019-01-28T10:27:27.680 回答
1

class Contact extends React.PureComponent {
  state = { firstName: "" };

  handleInput = ({ target }, name) => {
    const newState = {...this.state,[name]:target.value};
    this.setState(newState);
  };

  render() {
    return (
      <div>
      <p>{this.state.firstName}</p>
      <input
        onChange={e => {
          this.handleInput(e, "firstName");
        }}
        value={this.state.firsName}
      />
      </div>
    );
  }
}

ReactDOM.render(<Contact />,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

于 2019-01-28T10:32:58.110 回答