所以我一直在学习反应,但是我在表单方面遇到了麻烦。
点击表单中的按钮后,我可以更改状态。但是,我只能找到显示如何警告新状态的资源。
如果我想将新状态呈现到DOM中怎么办?
我不一定需要答案,但我希望向自己展示资源以找出答案,以帮助我学习。
这就是我所拥有的:
import React from 'react';
import ReactDOM from 'react-dom';
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { username: '',};
}
myChangeHandler = (e) => {
this.setState ({username: e.target.value});
}
mySubmitHandler = () => {
alert(this.state.username);
}
render() {
return (
<form>
<p>Enter your name, and submit:</p>
<input
type='text'
onChange={this.myChangeHandler}
/>
<button onClick={this.mySubmitHandler}>Submit</button>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
答案 0 :(得分:0)
使状态显示为组件状态的一部分。
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { userNameForInput: '', userNameForDisplay: ''}; // add 'userNameForDisplay'
}
myChangeHandler = (e) => {
this.setState ({ userNameForInput: e.target.value });
}
mySubmitHandler = () => {
this.setState ({ userNameForDisplay: this.state.userNameForInput }); // update `userNameForDisplay` by 'userNameForInput'
}
render() {
const { userNameForInput, userNameForDisplay } = this.state
return (
<form>
<p>Enter your name, and submit:</p>
<input
type='text'
onChange={this.myChangeHandler}
/>
<button onClick={this.mySubmitHandler}>Submit</button>
{/* render 'userNameForInput', 'userNameForDisplay' to DOM */}
{/* the format to render js variable in jsx is '{ jsVariable }' */}
<div>UserName From Input(update by input change): { userNameForInput }<div>
<div>UserName For Submit(update by submit button): { userNameForDisplay }<div>
</form>
);
}
}