【发布时间】:2019-08-06 14:35:18
【问题描述】:
我是 React 的新手,并试图设置一个表单,在点击提交时,应该将组件状态设置为等于用户条目,以便我可以存储它并在其他地方引用它。这可以作为控制台在提交后记录正确的字符串。但是,当我尝试在屏幕上显示此状态时遇到了麻烦。
我尝试将状态作为道具传递给子组件并在那里渲染,但我遇到了同样的错误。
import React from 'react';
var hasSetMainGoal = false;
class LearningGoals extends React.Component {
constructor(props) {
super(props);
this.state = {
maingoal: ''
};
this.handleInput = this.handleInput.bind(this);
this.updateMainGoal = this.updateMainGoal.bind(this);
}
handleInput(e) {
this.setState({ maingoal: e.target.value });
}
updateMainGoal = ({ target }) => {
this.setState({ maingoal: target});
console.log('My main goal is ' + this.state.maingoal);
hasSetMainGoal = true;
}
render() {
if (!hasSetMainGoal) {
return (
<div>
<div className='setGoals'>
<div className='formField'>
<label className='formFieldLabel'>What is your main learning goal?</label>
<input type='text' id='mainGoal' className='formFieldInput'
placeholder='' name='maingoal' value={this.state.value} onChange={this.handleInput} />
</div>
<div>
<button onClick={this.updateMainGoal}>Submit</button>
</div>
</div>
</div>
);
}
else if (hasSetMainGoal) {
return (
<div>
<h1>My main goal is {this.state.maingoal}</h1>
</div>
);
}
}
}
export default LearningGoals;
我希望在屏幕上显示{this.state.maingoal},但我收到以下错误:
react-dom.development.js:57 Uncaught Invariant Violation:对象作为 React 子级无效(发现:[object HTMLButtonElement])。如果您打算渲染一组子项,请改用数组。 在 h1 中(在 SetGoals.js:55) 在 div 中(在 SetGoals.js:54)
【问题讨论】:
-
在提交表单时,您传递的是
target,它是对象且不可渲染。为什么还要通过输入和按钮设置状态?顺便提一句。在按钮中使用type='button'或添加e.preventDefault()来处理以防止表单提交时重定向。
标签: reactjs