为什么在受控输入更改时没有呈现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} />
)
}
}
它应该在输入时呈现新状态, 但这不是
答案 0 :(得分: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
属性。
答案 1 :(得分: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>