[英]React component not rerender on state change
I'm rendering the following form component twice in an other component. 我在另一个组件中两次渲染以下表单组件。 Problem is that when I enter a value in one of the rendered forms, it doesn't update the placeholder of the other form.
问题是,当我以一种呈现形式输入值时,它不会更新另一种形式的占位符。 How do I get react to re-render component after state change so that both forms have the same placeholder value?
状态更改后如何对重新渲染组件做出反应,以使两种形式具有相同的占位符值?
Here's a fiddle: https://jsfiddle.net/o4h5af4g/7/ 这是一个小提琴: 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;
I think you just missed to initialize the input (input's value property) with the value from your state. 我认为您只是错过了使用状态值初始化输入(输入的value属性)的问题。 This should trigger the re-render
这应该触发重新渲染
<input name="length" onChange={this.handleChange.bind(this)}
type="integer" placeholder={this.state.length}
value={this.state.length} />
Another flaw in your code is the constructor. 您代码中的另一个缺陷是构造函数。 You should set props first thing.
您应该首先设置道具。
constructor(props){
super(props);
this.state = { length: 1 };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.