4 回答

TA貢獻1786條經驗 獲得超13個贊
您可以使用useRef或defaultValue
import React, { useRef, useEffect } from "react";
const input = useRef();
useEffect(() => {
input.current.value = "[email protected]";
}, []);
<input ref={input} className="form-input" type="text" name="email" />`

TA貢獻1786條經驗 獲得超11個贊
在狀態對象內設置默認值并將更改處理程序附加到輸入以捕獲更改:
示例codesandbox:https://codesandbox.io/s/react-basic-class-component-22fl7
class Demo extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: '[email protected]'
};
}
handleChange = event => {
this.setState({ inputValue: event.target.value }, () =>
console.log(this.state.inputValue)
);
};
render() {
return (
<div className="form-group">
<label>Email:</label>
<input
className="form-input"
type="text"
value={this.state.inputValue}
onChange={this.handleChange}
name="email">
</input>
</div>
);
}
}

TA貢獻1780條經驗 獲得超5個贊
這是如何在反應中使用輸入的示例代碼
class NameForm 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});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
- 4 回答
- 0 關注
- 136 瀏覽
添加回答
舉報