[英]React component not rerender on state change
我在另一個組件中兩次渲染以下表單組件。 問題是,當我以一種呈現形式輸入值時,它不會更新另一種形式的占位符。 狀態更改后如何對重新渲染組件做出反應,以使兩種形式具有相同的占位符值?
這是一個小提琴: https : //jsfiddle.net/o4h5af4g/7/
import React, { Component } from 'react';
class LengthForm extends Component {
constructor(props){
super(props)
this.state = {
length:1
};
}
handleChange(event) {
this.setState({length: event.target.value});
}
render() {
return (
<div className="LenghtForm">
<input name="length" onChange={this.handleChange.bind(this)} type="integer" placeholder={this.state.length}/>
</div>
);
}
}
export default LengthForm;
我認為您只是錯過了使用狀態值初始化輸入(輸入的value屬性)的問題。 這應該觸發重新渲染
<input name="length" onChange={this.handleChange.bind(this)}
type="integer" placeholder={this.state.length}
value={this.state.length} />
您代碼中的另一個缺陷是構造函數。 您應該首先設置道具。
constructor(props){
super(props);
this.state = { length: 1 };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.