在输入标记中放置了value属性时,它没有从键盘输入而未显示输入
import React from 'react'
class Postform extends React.Component {
state = {
name: 'helo',
email: '',
password: '',
bio: '',
};
changeHandler = (event) => {};
submitHandler = (event) => {
event.preventDefault();
};
render() {
return (
<div className="container">
<form onSubmit={this.submitHandler}>
<div classNam=" form-group ">
<label htmlFor="name">Enter your name </label>
<input
placeholder="Enter your name"
id="name"
className="form-control"
name="name"
onChange={this.changeHandler}
value="hello"
/>
</div>
<button type="submit" className="btn btn-info">
submit
</button>
</form>
</div>
);
}
}
export default Postform;
答案 0 :(得分:0)
您将输入value
设置为hello
,这意味着无论如何它将保持hello
。
要使输入value
动态,您需要将组件state
中的值设置为输入value
。
这意味着当输入state
使用value
更改时,您还必须更新changeHandler
。
让我们从输入开始
// Always read the input value from state
// and when the input value changes call this.changeHandler
<input onChange={this.changeHandler} value={this.state.name} />
然后changeHandler
changeHandler = (event) => {
// The input value has been changed, get the value from
// event.target.value and set it as state.
this.setState({ name: event.target.value });
};
现在state
将被更新,组件将以当前re-render
作为值state.name
的输入