【发布时间】:2018-04-19 16:11:30
【问题描述】:
请附上一支笔 https://codepen.io/Kiszuriwalilibori/pen/qYEYOO?editors=1111
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { meta: 'x' };
this.changeName = this.changeName.bind(this);
}
changeName(newName) {
this.setState({
meta: newName
});
}
render() {
console.log('parent-meta '+this.state.meta);
return (
<div>
<Meta onSubmit={this.changeName} />
<h1>Parent</h1>
</div>
);
}
}
class Meta extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value.split(/\D/).join('') });
console.log('handleChange wykonane');
}
handleSubmit(event) {//to jest odpowiednik handlechange
const dupa= this.state.value;
console.log ('dupa '+ dupa);
this.props.onSubmit(dupa);
console.log('handlesubmit this.state.value'+ this.state.value);//onSubmit musi olecieć wyżej i byc ma ztym dziecko wywoływane
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" /> <br/>
Binded attr to input: {this.state.value}
</form>
);
}
}
ReactDOM.render(<Parent />, document.getElementById("root"));
问题是:
您在这里看到相对简单的 Parent 和 Meta React 类。 父渲染 Meta 打开一个表单。表单有提交按钮,在提交按钮被按下后,父级将输入字符串变为其状态。
但是,实际上后来发生的事情是相当不受欢迎的(至少从我的角度来看,代码的逻辑可能完全不同)。 Parent 确实从 Meta 中获取值,但在几秒钟内“好”值消失并取回默认值。我还观察到,只要提交按钮处于活动状态,就会保持良好的价值。 我宁愿保留好的价值,如何保留不受欢迎的清爽?
【问题讨论】:
-
您在所述元素的渲染中返回了
Parent组件。这触发了我的警报。我不确定是否可以这样做 -
你在哪里使用该值
state.meta在视图中?如果它没有被使用,不要指望它会保存。 -
请解释清楚一点,很难理解
标签: javascript reactjs